Exemple #1
1
        public Customer getCustomer(String customerId)
        {
            eConnectMethods eConnect = new eConnectMethods();
            String address1 = "";
            String address2 = "";
            Customer result = new Customer();
            result.CustomerID = customerId;
            try
            {

                eConnectType myEConnectType = new eConnectType();
                RQeConnectOutType myReqType = new RQeConnectOutType();
                eConnectOut myeConnectOut = new eConnectOut();
                myeConnectOut.ACTION = 1;
                myeConnectOut.DOCTYPE = "Customer";
                myeConnectOut.OUTPUTTYPE = 2;
                myeConnectOut.INDEX1FROM = customerId;
                myeConnectOut.INDEX1TO = customerId;
                myeConnectOut.FORLIST = 1;
                // Add the eConnectOut XML node object to the RQeConnectOutType schema object
                myReqType.eConnectOut = myeConnectOut;

                // Add the RQeConnectOutType schema object to the eConnect document object
                RQeConnectOutType[] myReqOutType = { myReqType };
                myEConnectType.RQeConnectOutType = myReqOutType;

                // Serialize the eConnect document object to a memory stream
                MemoryStream myMemStream = new MemoryStream();
                XmlSerializer mySerializer = new XmlSerializer(myEConnectType.GetType());
                mySerializer.Serialize(myMemStream, myEConnectType);
                myMemStream.Position = 0;

                // Load the serialized eConnect document object into an XML document object
                XmlTextReader xmlreader = new XmlTextReader(myMemStream);
                XmlDocument myXmlDocument = new XmlDocument();
                myXmlDocument.Load(xmlreader);

                // Call the eConnect_Requester method of the eConnectMethods object to retrieve specified XML data
                string reqDoc = eConnect.eConnect_Requester(sConnectionString, EnumTypes.ConnectionStringType.SqlClient, myXmlDocument.OuterXml);
                XmlDocument resultDocument = new XmlDocument();
                resultDocument.LoadXml(reqDoc);

                XmlNodeList customerNodeList = resultDocument.GetElementsByTagName("Customer");

                if (customerNodeList.Count == 0) return null;
                else
                {
                    //Here we have retrieved the customer document
                    foreach (XmlNode node in customerNodeList[0])
                    {
                        if (node.Name.Equals("ADDRESS1"))
                            address1 = node.InnerText;
                        if (node.Name.Equals("ADDRESS2"))
                            address2 = node.InnerText;
                        else if (node.Name.Equals("ADRSCODE"))
                            result.CustomerAddress.AddressCode = node.InnerText;
                        else if (node.Name.Equals("CITY"))
                            result.CustomerAddress.City = node.InnerText;
                        else if (node.Name.Equals("CNTCPRSN"))
                            result.CustomerAddress.AddressContact = node.InnerText;
                        else if (node.Name.Equals("COUNTRY"))
                            result.CustomerAddress.Country = node.InnerText;
                        else if (node.Name.Equals("CUSTCLAS"))
                            result.CustomerClass = node.InnerText;
                        else if (node.Name.Equals("CUSTNAME"))
                            result.CustomerName = node.InnerText;
                        else if (node.Name.Equals("PHONE1"))
                            result.CustomerAddress.PhoneNumber1 = node.InnerText;
                        else if (node.Name.Equals("PHONE2"))
                            result.CustomerAddress.PhoneNumber2 = node.InnerText;
                        else if (node.Name.Equals("FAX"))
                            result.CustomerAddress.FaxNumber = node.InnerText;
                        else if (node.Name.Equals("STATE"))
                            result.CustomerAddress.State = node.InnerText;
                        else if (node.Name.Equals("ZIP"))
                            result.CustomerAddress.Zipcode = node.InnerText;
                        else if (node.Name.Equals("STMTNAME"))
                            result.StatementName = node.InnerText;
                        else if (node.Name.Equals("SHRTNAME"))
                            result.ShortName = node.InnerText;
                        else if (node.Name.Equals("PRBTADCD"))
                            result.BillTo = node.InnerText;
                        else if (node.Name.Equals("PRSTADCD"))
                            result.ShipTo = node.InnerText;
                        else if (node.Name.Equals("STADDRCD"))
                            result.StatementTo = node.InnerText;
                        else if (node.Name.Equals("USERDEF1"))
                            result.Type = node.InnerText;
                        else if (node.Name.Equals("USERDEF2"))
                            result.StudentStatus = node.InnerText;
                        else if (node.Name.Equals("INACTIVE"))
                            if (node.InnerText.Equals("1")) result.Inactive = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            result.CustomerAddress.AddressString = address1 + address2;
            return result;
        }
        private string SerializeSalesPerson(taCreateSalesperson salesperson)
        {
            try
            {
                RMSalespersonMasterType salespersonType = new RMSalespersonMasterType();
                eConnectType            eConnect        = new eConnectType();
                salespersonType.taCreateSalesperson = salesperson;

                RMSalespersonMasterType[] rmsalesperson = { salespersonType };

                eConnect.RMSalespersonMasterType = rmsalesperson;

                MemoryStream ms = new MemoryStream();

                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());
                serializer.Serialize(ms, eConnect);
                ms.Position = 0;
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(ms);

                string SalespersonEntity = xmldoc.OuterXml;
                return(SalespersonEntity);
            }
            catch (XmlException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #3
0
        /*
         * /// <summary>
         * ///
         * /// </summary>
         * /// <param name="vendor"></param>
         * /// <returns></returns>
         * private string SerializeVendor(taUpdateCreateVendorRcd vendor)
         * {
         *  try
         *  {
         *      PMVendorMasterType VendorMasterType = new PMVendorMasterType();
         *      eConnectType eConnect = new eConnectType();
         *      VendorMasterType.taUpdateCreateVendorRcd = vendor;
         *      PMVendorMasterType[] VendorsMasterType = { VendorMasterType };
         *
         *      eConnect.PMVendorMasterType = VendorsMasterType;
         *
         *      //MemoryStream ms = new MemoryStream();
         *      FileStream FS = new FileStream(@"C:\DOCS\eConnectVendor.xml", FileMode.Create);
         *
         *      XmlTextWriter writer = new XmlTextWriter(FS, new UTF8Encoding());
         *
         *      XmlSerializer serializer = new XmlSerializer(eConnect.GetType());
         *      serializer.Serialize(writer, eConnect);
         *      writer.Close();
         *
         *      XmlDocument xmldoc = new XmlDocument();
         *
         *
         *      xmldoc.Load(@"C:\DOCS\eConnectVendor.xml");
         *
         *      string VendorEntity = xmldoc.OuterXml;
         *
         *      File.Delete(@"C:\DOCS\eConnectVendor.xml");
         *
         *      return VendorEntity;
         *
         *  }
         *  catch (XmlException)
         *  {
         *      throw;
         *  }
         *  catch (Exception)
         *  {
         *
         *      throw;
         *  }
         *
         *
         * }
         */


        /// <summary>
        ///
        /// </summary>
        /// <param name="vendor"></param>
        /// <returns></returns>
        private string SerializeVendor(taUpdateCreateVendorRcd vendor)
        {
            try
            {
                PMVendorMasterType VendorMasterType = new PMVendorMasterType();
                eConnectType       eConnect         = new eConnectType();
                VendorMasterType.taUpdateCreateVendorRcd = vendor;
                PMVendorMasterType[] VendorsMasterType = { VendorMasterType };

                eConnect.PMVendorMasterType = VendorsMasterType;

                MemoryStream ms = new MemoryStream();

                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());
                serializer.Serialize(ms, eConnect);
                ms.Position = 0;
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(ms);
                string VendorEntity = xmldoc.OuterXml;
                return(VendorEntity);
            }
            catch (XmlException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
        //public Decimal getImpuestos(string id)
        //{
        //    tx00201 impuestos = new tx00201(DatosConexionDB.Elemento.ConnStr);
        //    try
        //    {
        //        if (impuestos.LoadByPrimaryKey(id))
        //        {
        //            return impuestos.TXDTLPCT;
        //        }
        //        else
        //            return 0;
        //    }
        //    catch
        //    {
        //        return 0;
        //    }
        //}

        /// <summary>
        /// Construye documento xml en un xmlDocument.
        /// </summary>
        /// <param name="eConnect"></param>
        public void serializa(eConnectType eConnect)
        {
            try
            {
                iError   = 0;
                _sDocXml = "";
                _xDocXml = new XmlDocument();
                StringBuilder sbDocXml = new StringBuilder();

                XmlSerializer     serializer = new XmlSerializer(eConnect.GetType());
                XmlWriterSettings sett       = new XmlWriterSettings();
                sett.Encoding = new UTF8Encoding();  //UTF8Encoding.UTF8; // Encoding.UTF8;
                using (XmlWriter writer = XmlWriter.Create(sbDocXml, sett))
                {
                    serializer.Serialize(writer, eConnect);
                    _sDocXml = sbDocXml.ToString();
                    _xDocXml.LoadXml(_sDocXml);
                }
            }
            catch (Exception errorGral)
            {
                sMensaje = "Error al serializar el documento. " + errorGral.Message + " [Serializa]";
                iError++;
            }
        }
        private string SerializeCustomerChild(taUpdateCreateCustomerRcd rmcustomer, taParentIDChild_ItemsTaParentIDChild[] rmchildren)
        {
            try
            {
                RMCustomerMasterType customerMasterType = new RMCustomerMasterType();
                eConnectType         eConnect           = new eConnectType();
                customerMasterType.taUpdateCreateCustomerRcd = rmcustomer;
                //customerMasterType.taCreateParentID = rmparent;
                customerMasterType.taParentIDChild_Items = rmchildren;

                RMCustomerMasterType[] Customers = { customerMasterType };

                eConnect.RMCustomerMasterType = Customers;
                MemoryStream ms = new MemoryStream();

                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());
                serializer.Serialize(ms, eConnect);
                ms.Position = 0;
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(ms);

                string CustomerEntity = xmldoc.OuterXml;
                return(CustomerEntity);
            }
            catch (XmlException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #6
0
        private string SerializeCustomerClass(taCreateCustomerClass customerClass)
        {
            try
            {
                RMCustomerClassType classType = new RMCustomerClassType();
                eConnectType        eConnect  = new eConnectType();
                classType.taCreateCustomerClass = customerClass;
                RMCustomerClassType[] rmClassType = { classType };

                eConnect.RMCustomerClassType = rmClassType;

                MemoryStream ms = new MemoryStream();

                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());
                serializer.Serialize(ms, eConnect);
                ms.Position = 0;
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(ms);

                string CustomerClassEntity = xmldoc.OuterXml;

                return(CustomerClassEntity);
            }
            catch (XmlException)
            {
                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="TransactionType"></param>
        /// <returns></returns>
        private string SerializeGLTransacion(GLTransactionType TransactionType)
        {
            try
            {
                eConnectType eConnect = new eConnectType();

                GLTransactionType[] tranType = { TransactionType };
                eConnect.GLTransactionType = tranType;
                MemoryStream ms = new MemoryStream();

                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());
                serializer.Serialize(ms, eConnect);
                ms.Position = 0;
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(ms);

                string TransactionXML = xmldoc.OuterXml;

                return(TransactionXML);
            }
            catch (Exception)
            {
                throw;
            }
        }
        private string SerializeRMVoid(RMVoidTransactionType rmvoid)
        {
            try
            {
                eConnectType            eConnect = new eConnectType();
                RMVoidTransactionType[] TranType = { rmvoid };
                eConnect.RMVoidTransactionType = TranType;

                MemoryStream ms = new MemoryStream();

                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());
                serializer.Serialize(ms, eConnect);
                ms.Position = 0;
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(ms);

                string TransactionXML = xmldoc.OuterXml;

                return(TransactionXML);
            }
            catch (Exception)
            {
                // logW.LogExeption("Econnect", 2, ex);
                throw;
            }
        }
        public APInvoiceResponseDto ImportGPInvoice(taPMTransactionInsert pmTransaction)
        {
            var response = new APInvoiceResponseDto();

            try
            {
                var PMTransaction = new PMTransactionType();
                PMTransaction.taPMTransactionInsert = pmTransaction;

                PMTransactionType[] PMTransType = { PMTransaction };

                eConnectType eConnect = new eConnectType();
                eConnect.PMTransactionType = PMTransType;

                MemoryStream  memStream  = new MemoryStream();
                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());
                serializer.Serialize(memStream, eConnect);
                memStream.Position = 0;

                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(memStream);
                memStream.Close();

                string finalXML = xmlDocument.OuterXml;

                string responseMessage = string.Empty;
                string errorMessage    = string.Empty;

                string voucher   = pmTransaction.VCHNUMWK;
                string docNumber = pmTransaction.DOCNUMBR;
                string vendorID  = pmTransaction.VENDORID;

                bool success = eConn.CreateTransactionEntity(ref responseMessage, finalXML, _config.Value.GPCompanyDB);

                response.Success   = success;
                response.ErrorCode = 0;

                if (success)
                {
                    response.Message = "Vendor " + vendorID + " invoice " + docNumber + " imported as voucher " + voucher;
                }
                else
                {
                    errorMessage       = "Failed to import vendor " + vendorID + " invoice " + docNumber + ": " + responseMessage;
                    response.Message   = errorMessage;
                    response.ErrorCode = LoggingEvents.INSERT_INVOICE_FAILED;
                }

                return(response);
            }
            catch (Exception ex)
            {
                response.Success   = false;
                response.ErrorCode = LoggingEvents.INSERT_INVOICE_EXCEPTION;
                response.Message   = "An unexpected error occured in ImportGPInvoice: " + ex.Message;
                return(response);
            }
        }
Exemple #10
0
		static void Main()
		{
			try
			{
				// Create an eConnect document type object
                eConnectType myEConnectType = new eConnectType();

                // Create a RQeConnectOutType schema object
				RQeConnectOutType myReqType = new RQeConnectOutType();
				
                // Create an eConnectOut XML node object
                eConnectOut myeConnectOut = new eConnectOut();

                // Populate the eConnectOut XML node elements
				myeConnectOut.ACTION = 1;
				myeConnectOut.DOCTYPE = "Customer";
				myeConnectOut.OUTPUTTYPE = 2;
				myeConnectOut.INDEX1FROM = "AARONFIT0001";
				myeConnectOut.INDEX1TO = "AARONFIT0001";
				myeConnectOut.FORLIST = 1;
			
				// Add the eConnectOut XML node object to the RQeConnectOutType schema object
                myReqType.eConnectOut = myeConnectOut;

                // Add the RQeConnectOutType schema object to the eConnect document object
				RQeConnectOutType [] myReqOutType = {myReqType};
				myEConnectType.RQeConnectOutType = myReqOutType;

                // Serialize the eConnect document object to a memory stream
				MemoryStream myMemStream = new MemoryStream();
				XmlSerializer mySerializer = new XmlSerializer(myEConnectType.GetType());
				mySerializer.Serialize(myMemStream, myEConnectType);
				myMemStream.Position = 0;

				// Load the serialized eConnect document object into an XML document object
                XmlTextReader xmlreader = new XmlTextReader(myMemStream);
                XmlDocument myXmlDocument = new XmlDocument();
                myXmlDocument.Load(xmlreader);

				// Create a connection string to specify the Microsoft Dynamics GP server and database
                // Change the data source and initial catalog to specify your server and database
                string sConnectionString = @"data source=MYSERVER;initial catalog=TWO;integrated security=SSPI;persist security info=False;packet size=4096";
				
                // Create an eConnectMethods object
                eConnectMethods requester = new eConnectMethods();
				
                // Call the eConnect_Requester method of the eConnectMethods object to retrieve specified XML data
                string reqDoc = requester.eConnect_Requester(sConnectionString, EnumTypes.ConnectionStringType.SqlClient, myXmlDocument.OuterXml);

                // Display the result of the eConnect_Requester method call
                Console.Write(reqDoc);
			}
			catch (Exception ex)
			{// Dislay any errors that occur to the console
				Console.Write(ex.ToString());
			}
		}
Exemple #11
0
        private static void serializeObject(string filename, part newpart)
        {
            // Create a datetime format object
            DateTimeFormatInfo dateFormat = new CultureInfo("en-US").DateTimeFormat;

            try
            {
                //create an eConnect schema object
                IVItemMasterType iv = new IVItemMasterType();

                taUpdateCreateItemRcd newItem = new taUpdateCreateItemRcd();


                newItem.ITEMNMBR          = newpart.itemNumber;  //Item number
                newItem.ITEMDESC          = newpart.description; //Item description
                newItem.ITMSHNAM          = "temp";              //short desc
                newItem.ITMGEDSC          = "temp";              //general desc
                newItem.UseItemClass      = 1;
                newItem.ITMCLSCD          = newpart.category;    //Part or Assembly
                newItem.ITEMTYPESpecified = true;                //Say custom itemtype is being used
                newItem.ITEMTYPE          = 1;                   //Sales item
                newItem.UOMSCHDL          = newpart.units;
                newItem.DECPLCURSpecified = true;                //Say a custom decplcur is being used
                newItem.DECPLCUR          = 3;                   //Needed to make item in IVR10015
                newItem.NOTETEXT          = newpart.purchasing;
                newItem.UpdateIfExists    = 0;

                //Populate schema object with newItem info
                iv.taUpdateCreateItemRcd = newItem;

                // Create an array that holds ItemMasterType objects
                // Populate the array with the ItemMasterType schema object
                IVItemMasterType[] myItemType = { iv };

                // Create an eConnect XML document object and populate it
                // with the ItemMasterType schema object
                eConnectType eConnect = new eConnectType();
                eConnect.IVItemMasterType = myItemType;

                // Create a file to hold the serialized eConnect XML document
                FileStream    fs     = new FileStream(filename, FileMode.Create);
                XmlTextWriter writer = new XmlTextWriter(fs, new UTF8Encoding());

                // Serialize the eConnect document object to the file using the XmlTextWriter.
                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());
                serializer.Serialize(writer, eConnect);
                writer.Close();
            }
            //If an eConnect exception occurs, notify the user
            catch (eConnectException ex)
            {
                Console.Write(ex.ToString());
            }
        }
        /// <summary>
        /// Crea el xml de un pago manual PM a partir de una fila de datos en una hoja excel.
        /// </summary>
        /// <param name="hojaXl">Hoja excel</param>
        /// <param name="filaXl">Fila de la hoja excel a procesar</param>
        public void integraPagoPM(ExcelWorksheet hojaXl, int filaXl, string sTimeStamp)
        {
            this.iError = 0;
            eConnectType docEConnectPM = new eConnectType();
            PagoManualPM pago          = new PagoManualPM(_DatosConexionDB);

            try
            {
                //Prepara pago
                pago.preparaPagoPM(hojaXl, filaXl, sTimeStamp, _Param);
                this._filaNuevaFactura = pago.iniciaNuevoDocEn;
                this.sMensajeDocu      = "Fila: " + filaXl.ToString() + " Número Doc: " + pago.pagoPm.DOCNUMBR + " Proveedor: " + pago.pagoPm.VENDORID + " Monto: " + pago.pagoPm.DOCAMNT.ToString();

                if (this.iError == 0 && pago.iError != 0)
                {
                    this.sMensaje = pago.sMensaje;
                    this.iError++;
                }

                //Ingresa el pago a GP
                if (this.iError == 0)
                {
                    docEConnectPM.PMManualCheckType = pago.arrPagoPmType;
                    this.serializa(docEConnectPM);

                    //debug!!!!
                    //this.iError++;
                    //sMensaje = _sDocXml;

                    if (this.iError == 0)
                    {
                        this.integraTransactionXml();
                    }
                }
            }
            catch (eConnectException eConnErr)
            {
                sMensaje = "Excepción al preparar el pago. " + eConnErr.Message + " " + eConnErr.TargetSite.ToString();
                iError++;
            }
            catch (ApplicationException ex)
            {
                sMensaje = "Excepción de aplicación. " + ex.Message + " " + ex.TargetSite.ToString();
                iError++;
            }
            catch (Exception errorGral)
            {
                sMensaje = "Excepción. " + errorGral.Message + " " + errorGral.TargetSite.ToString();
                iError++;
            }
        }
Exemple #13
0
        /// <summary>
        /// serialize customer address
        /// </summary>
        /// <param name="filename"></param>
        public static void SerializeCustomerAddressObject(string filename)
        {
            try
            {
                // Instantiate an eConnectType schema object
                eConnectType eConnect = new eConnectType();

                // Instantiate a RMCustomerAddressType schema object
                RMCustomerAddressType addressType = new RMCustomerAddressType();

                // Instantiate a taCreateCustomerAddress_ItemsTaCreateCustomerAddress XML node object
                taCreateCustomerAddress_ItemsTaCreateCustomerAddress address = new taCreateCustomerAddress_ItemsTaCreateCustomerAddress();

                // Create an XML serializer object
                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());

                // Populate elements of the taUpdateCreateCustomerRcd XML node object
                address.CUSTNMBR = "Customer001";
                //address.CUSTNAME = "Customer 1";
                //address.ADDRESS1 = "2002 60th St SW";
                //address.ADRSCODE = "Primary";
                //address.CITY = "NewCity";
                //address.ZIPCODE = "52302";

                // Populate the RMCustomerAddressType schema with the taCreateCustomerAddress_ItemsTaCreateCustomerAddress XML node
                addressType.taCreateCustomerAddress_Items = new taCreateCustomerAddress_ItemsTaCreateCustomerAddress[1] {
                    address
                };
                RMCustomerAddressType[] customerAddress = { addressType };

                // Populate the eConnectType object with the RMCustomerAddressType schema object
                eConnect.RMCustomerAddressType = customerAddress;

                // Create objects to create file and write the customer XML to the file
                FileStream    fs     = new FileStream(filename, FileMode.Create);
                XmlTextWriter writer = new XmlTextWriter(fs, new UTF8Encoding());

                // Serialize the eConnectType object to a file using the XmlTextWriter.
                serializer.Serialize(writer, eConnect);
                writer.Close();
            }
            // catch any errors that occur and display them to the console
            catch (System.Exception ex)
            {
                Console.Write(ex.ToString());
            }
        }
        /// <summary>
        /// Crea el xml de una factura sop a partir de una vista sql.
        /// </summary>
        private taSopHdrIvcInsert IntegraFacturaSOP(vwIntegracionesVentas preFacturasAIntegrar, string sTimeStamp)
        {
            string       eConnResult                = String.Empty;
            eConnectType docEConnectSOP             = new eConnectType();
            eConnectType entEconnect                = new eConnectType();
            FacturaDeVentaSOPBandejaDB documentoSOP = new FacturaDeVentaSOPBandejaDB(parametrosDB);
            eConnectMethods            eConnObject  = new eConnectMethods();

            var    dpf = getPrefacturasDetalle(preFacturasAIntegrar.NUMDOCARN, preFacturasAIntegrar.TIPODOCARN);
            string tipoContribuyente = LocArgentina_GetTipoContribuyente(preFacturasAIntegrar.IDCLIENTE);

            documentoSOP.preparaFacturaSOP(preFacturasAIntegrar, dpf, sTimeStamp, tipoContribuyente);
            docEConnectSOP.SOPTransactionType = new SOPTransactionType[] { documentoSOP.FacturaSop };
            serializa(docEConnectSOP);
            eConnResult = eConnObject.CreateTransactionEntity(parametrosDB.ConnStringTarget, this.SDocXml);
            return(documentoSOP.FacturaSop.taSopHdrIvcInsert);
        }
Exemple #15
0
        /// <summary>
        /// serialize payables object
        /// </summary>
        /// <param name="filename"></param>
        public static void SerializePayablesObject(string filename)
        {
            try
            {
                // Instantiate an eConnectType schema object
                eConnectType eConnect = new eConnectType();

                // Instantiate a PMTransactionType  schema object
                PMTransactionType transactionType = new PMTransactionType();

                // Instantiate a taPMTransactionInsert XML node object
                taPMTransactionInsert transaction = new taPMTransactionInsert();

                // Create an XML serializer object
                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());

                // Populate elements of the taPMTransactionInsert XML node object
                //transaction.CUSTNMBR = "Customer001";
                //transaction.CUSTNAME = "Customer 1";
                //transaction.ADDRESS1 = "2002 60th St SW";
                //transaction.ADRSCODE = "Primary";
                //transaction.CITY = "NewCity";
                //transaction.ZIPCODE = "52302";

                // Populate the PMTransactionType schema with the taPMTransactionInsert XML node
                transactionType.taPMTransactionInsert = transaction;
                PMTransactionType[] payablesTransaction = { transactionType };

                // Populate the eConnectType object with the PMTransactionType schema object
                eConnect.PMTransactionType = payablesTransaction;

                // Create objects to create file and write the customer XML to the file
                FileStream    fs     = new FileStream(filename, FileMode.Create);
                XmlTextWriter writer = new XmlTextWriter(fs, new UTF8Encoding());

                // Serialize the eConnectType object to a file using the XmlTextWriter.
                serializer.Serialize(writer, eConnect);
                writer.Close();
            }
            // catch any errors that occur and display them to the console
            catch (System.Exception ex)
            {
                Console.Write(ex.ToString());
            }
        }
Exemple #16
0
        /// <summary>
        /// serialize item
        /// </summary>
        /// <param name="filename"></param>
        public static void SerializeItemObject(string filename)
        {
            try
            {
                // Instantiate an eConnectType schema object
                eConnectType eConnect = new eConnectType();

                // Instantiate a IVItemMasterType  schema object
                IVItemMasterType itemType = new IVItemMasterType();

                // Instantiate a taUpdateCreateItemRcd XML node object
                taUpdateCreateItemRcd item = new taUpdateCreateItemRcd();

                // Create an XML serializer object
                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());

                // Populate elements of the taUpdateCreateVendorRcd XML node object
                //item.CUSTNMBR = "Customer001";
                //item.CUSTNAME = "Customer 1";
                //item.ADDRESS1 = "2002 60th St SW";
                //item.ADRSCODE = "Primary";
                //item.CITY = "NewCity";
                //item.ZIPCODE = "52302";

                // Populate the IVItemMasterType schema with the taUpdateCreateItemRcd XML node
                itemType.taUpdateCreateItemRcd = item;
                IVItemMasterType[] itemMaster = { itemType };

                // Populate the eConnectType object with the IVItemMasterType schema object
                eConnect.IVItemMasterType = itemMaster;

                // Create objects to create file and write the customer XML to the file
                FileStream    fs     = new FileStream(filename, FileMode.Create);
                XmlTextWriter writer = new XmlTextWriter(fs, new UTF8Encoding());

                // Serialize the eConnectType object to a file using the XmlTextWriter.
                serializer.Serialize(writer, eConnect);
                writer.Close();
            }
            // catch any errors that occur and display them to the console
            catch (System.Exception ex)
            {
                Console.Write(ex.ToString());
            }
        }
Exemple #17
0
        /// <summary>
        /// serialize vendor
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="foundry"></param>
        public static void SerializeVendorObject(string filename, PM00200_Foundry foundry)
        {
            try
            {
                // Instantiate an eConnectType schema object
                eConnectType eConnect = new eConnectType();

                // Instantiate a PMVendorMasterType schema object
                PMVendorMasterType vendortype = new PMVendorMasterType();

                // Instantiate a taUpdateCreateCustomerRcd XML node object
                taUpdateCreateVendorRcd vendor = new taUpdateCreateVendorRcd();

                // Create an XML serializer object
                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());

                //Populate elements of the taUpdateCreateVendorRcd XML node object
                vendor.VENDORID       = foundry.VENDORID;
                vendor.VENDNAME       = foundry.VENDNAME;
                vendor.VENDSHNM       = foundry.VENDSHNM;
                vendor.UseVendorClass = 1;
                vendor.VNDCLSID       = "SUO";

                // Populate the PMVendorMasterType schema with the taUpdateCreateVendorRcd XML node
                vendortype.taUpdateCreateVendorRcd = vendor;
                PMVendorMasterType[] vendorMaster = { vendortype };

                // Populate the eConnectType object with the PMVendorMasterType schema object
                eConnect.PMVendorMasterType = vendorMaster;

                // Create objects to create file and write the customer XML to the file
                FileStream    fs     = new FileStream(filename, FileMode.Create);
                XmlTextWriter writer = new XmlTextWriter(fs, new UTF8Encoding());

                // Serialize the eConnectType object to a file using the XmlTextWriter.
                serializer.Serialize(writer, eConnect);
                writer.Close();
            }
            // catch any errors that occur and display them to the console
            catch (System.Exception ex)
            {
                Console.Write(ex.ToString());
            }
        }
        /// <summary>
        /// Construye documento xml en un xmlDocument.
        /// </summary>
        /// <param name="eConnect"></param>
        public void serializa(eConnectType eConnect)
        {
            try
            {
                _sDocXml = "";
                _xDocXml = new XmlDocument();
                StringBuilder sbDocXml = new StringBuilder();

                XmlSerializer     serializer = new XmlSerializer(eConnect.GetType());
                XmlWriterSettings sett       = new XmlWriterSettings();
                sett.Encoding = new UTF8Encoding();  //UTF8Encoding.UTF8; // Encoding.UTF8;
                using (XmlWriter writer = XmlWriter.Create(sbDocXml, sett))
                {
                    serializer.Serialize(writer, eConnect);
                    _sDocXml = sbDocXml.ToString();
                    _xDocXml.LoadXml(_sDocXml);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public XmlDocument Serializa(eConnectType eConnect)
        {
            try
            {
                MemoryStream  memoryStream  = new MemoryStream();
                XmlSerializer xmlSerializer = new XmlSerializer(eConnect.GetType());

                xmlSerializer.Serialize(memoryStream, eConnect);

                memoryStream.Position = 0;

                // Create an XmlDocument from the serialized eConnectType in memory.
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(memoryStream);
                memoryStream.Close();

                return(xmlDocument);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #20
0
        private void serializeSOPObject(string filename, Transaction assessment, string documentID, string defaultSiteID)
        {
            try
            {
                taSopLineIvcInsert_ItemsTaSopLineIvcInsert itemLine;

                taSopLineIvcInsert_ItemsTaSopLineIvcInsert[] lineItems =
                    new taSopLineIvcInsert_ItemsTaSopLineIvcInsert[assessment.Items.Count];

                int r = 0;
                //populate item lines
                foreach (Item item in assessment.Items)
                {
                    itemLine =
                        new taSopLineIvcInsert_ItemsTaSopLineIvcInsert();

                    //item pks
                    itemLine.SOPTYPE = (short)assessment.TransactionType;
                    itemLine.CUSTNMBR = assessment.StudentID;
                    itemLine.SOPNUMBE = assessment.DocumentNumber;
                    itemLine.PRCLEVEL = assessment.PriceLevel; //20100527

                    itemLine.DOCID = documentID;
                    //item details
                    itemLine.ITEMNMBR = item.ItemNo;
                    itemLine.UOFM = item.Uofm;
                    if (assessment.TransactionType == Transaction_Type.Drop)
                    {
                        itemLine.QUANTITY = item.Qty;
                        itemLine.QTYINSVC = item.Qty;
                    }
                    else if (assessment.TransactionType == Transaction_Type.Assessment)
                    {
                        itemLine.QUOTEQTYTOINV = item.Qty;
                    }
                    else if (assessment.TransactionType == Transaction_Type.Add)
                    {
                        itemLine.QUANTITY = item.Qty;
                    }
                    itemLine.ITEMDESC = item.ItemDescription;
                    itemLine.UNITPRCE = item.Unitprice;
                    itemLine.MRKDNPCTSpecified = true;
                    itemLine.MRKDNPCT = item.MarkDown;

                    itemLine.XTNDPRCE = item.ExtendedPrice;
                    itemLine.LOCNCODE = defaultSiteID;
                    itemLine.DOCDATE = assessment.DocumentDate.ToShortDateString();

                    //itemLine.UpdateIfExists = 1;
                    lineItems[r] = itemLine;
                    r += 1;
                }
                //add items

                SOPTransactionType salesOrder = new SOPTransactionType();
                Array.Resize(ref salesOrder.taSopLineIvcInsert_Items, r);
                salesOrder.taSopLineIvcInsert_Items = lineItems;

                taSopHdrIvcInsert header = new taSopHdrIvcInsert();

                //populate header node
                header.SOPTYPE = (short)assessment.TransactionType;
                header.SOPNUMBE = assessment.DocumentNumber;
                header.DOCID = documentID;
                header.PRCLEVEL = assessment.PriceLevel; //20100527
                header.TRDISAMTSpecified = true;

                header.BACHNUMB = assessment.BatchID;
                header.LOCNCODE = defaultSiteID;
                header.CUSTNMBR = assessment.StudentID;
                header.CUSTNAME = assessment.StudentName;
                header.CURNCYID = assessment.CurrencyID;
                header.DOCDATE = assessment.DocumentDate.ToShortDateString();
                if (assessment.TransactionType == Transaction_Type.Assessment)
                {
                    header.QUOEXPDA = assessment.ExpirationDate.ToShortDateString();
                    header.INVODATE = assessment.DocumentDate.ToShortDateString();
                }
                header.CMMTTEXT = assessment.Comments;
                header.SUBTOTAL = assessment.Subtotal;
                header.TRDISAMT = assessment.TotalDiscounts;
                header.MISCAMNT = assessment.InstallmentFee;
                header.DOCAMNT = assessment.TotalAmount;
                header.USINGHEADERLEVELTAXES = 1;
                //header.DEFTAXSCHDS = 1;
                //header.UpdateExisting = 1;

                //add header

                salesOrder.taSopHdrIvcInsert = header;

                eConnectType eConnType = new eConnectType();
                Array.Resize(ref eConnType.SOPTransactionType, 1);
                eConnType.SOPTransactionType[0] = salesOrder;
                //serialization proper
                using (FileStream fs = new FileStream(filename, FileMode.Create))
                {
                    XmlTextWriter writer = new XmlTextWriter(fs, new UTF8Encoding());
                    XmlSerializer serializer = new XmlSerializer(eConnType.GetType());
                    serializer.Serialize(writer, eConnType);
                    writer.Close();
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }
        private void CreateVendorItem(string vendorID, string itemNumber)
        {
            eConnectType eConnect;

            try
            {
                taCreateItemVendors_ItemsTaCreateItemVendors record = new taCreateItemVendors_ItemsTaCreateItemVendors();
                record.ITEMNMBR = itemNumber;
                record.VENDORID = vendorID;

                IVVendorItemType curType = new IVVendorItemType();
                curType.taCreateItemVendors_Items = new taCreateItemVendors_ItemsTaCreateItemVendors[] { record };


                IVVendorItemType[] typeArray = new IVVendorItemType[] { curType };

                eConnect = new eConnectType(); 
                eConnect.IVVendorItemType = typeArray;

                //Serialize the XML document to the file
                XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, eConnect);

                DynamicsGP_ec.SendData(writer.ToString());
            }

            catch (Exception ex)
            {
                //ExceptionMngr.WriteEvent("CreateVendorItem: ", ListValues.EventType.Error, ex, null,
                    //ListValues.ErrorCategory.ErpConnection);

                throw new Exception("CreateVendorItem: "+ ex.Message);
            }

        }
        /// <summary>
        /// Crea el xml de una factura sop a partir de una fila de datos en una hoja excel.
        /// </summary>
        /// <param name="hojaXl">Hoja excel</param>
        /// <param name="filaXl">Fila de la hoja excel a procesar</param>
        public void IntegraFacturaSOP(ExcelWorksheet hojaXl, int filaXl, string sTimeStamp)
        {
            _iError  = 0;
            _mensaje = String.Empty;
            string            eConnResult    = String.Empty;
            eConnectType      docEConnectSOP = new eConnectType();
            eConnectType      entEconnect    = new eConnectType();
            FacturaDeVentaSOP documentoSOP   = new FacturaDeVentaSOP(_ParamExcel.ConnectionStringTargetEF);
            eConnectMethods   eConnObject    = new eConnectMethods();

            Cliente entidadCliente;

            try
            {
                _mensaje = " Número Doc: " + hojaXl.Cells[filaXl, _ParamExcel.FacturaSopnumbe].Value.ToString().Trim();

                entidadCliente = new Cliente(_ParamExcel.ConnectionStringTargetEF, _ParamExcel.FacturaSopTXRGNNUM.ToString(), _ParamExcel.FacturaSopCUSTNAME.ToString(), _ParamExcel.ClienteDefaultCUSTCLAS);
                if (entidadCliente.preparaClienteEconn(hojaXl, filaXl))
                {
                    entEconnect.RMCustomerMasterType = entidadCliente.ArrCustomerType;
                    serializa(entEconnect);
                    if (eConnObject.CreateEntity(_ParamExcel.ConnStringTarget, _sDocXml))
                    {
                        _mensaje += "--> Cliente Integrado a GP";
                    }
                }

                documentoSOP.preparaFacturaSOP(hojaXl, filaXl, sTimeStamp, _ParamExcel);
                docEConnectSOP.SOPTransactionType = new SOPTransactionType[] { documentoSOP.FacturaSop };
                serializa(docEConnectSOP);
                eConnResult  = eConnObject.CreateTransactionEntity(_ParamExcel.ConnStringTarget, _sDocXml);
                _sMensajeErr = "--> Integrado a GP";
            }
            catch (NullReferenceException nr)
            {
                string sInner = nr.InnerException == null ? String.Empty : nr.InnerException.Message;
                if (nr.InnerException != null)
                {
                    sInner += nr.InnerException.InnerException == null ? String.Empty : " " + nr.InnerException.InnerException.Message;
                }
                _sMensajeErr = "Excepción al validar datos de la factura SOP. " + nr.Message + " " + sInner + " [" + nr.TargetSite.ToString() + "]";
                _iError++;
            }
            catch (eConnectException eConnErr)
            {
                string sInner = eConnErr.InnerException == null ? String.Empty : eConnErr.InnerException.Message;
                _sMensajeErr = "Excepción eConnect al integrar factura SOP. " + eConnErr.Message + " " + sInner + " [" + eConnErr.TargetSite.ToString() + "]";
                _iError++;
            }
            catch (Exception errorGral)
            {
                string sInner = errorGral.InnerException == null ? String.Empty : errorGral.InnerException.Message;
                if (errorGral.InnerException != null)
                {
                    sInner += errorGral.InnerException.InnerException == null ? String.Empty : " " + errorGral.InnerException.InnerException.Message;
                }
                _sMensajeErr = "Excepción desconocida al integrar factura SOP. " + errorGral.Message + " " + sInner + " [" + errorGral.TargetSite.ToString() + "]";
                _iError++;
            }
            finally
            {
                _filaNuevaFactura = filaXl + 1;
                _mensaje          = "Fila: " + filaXl.ToString() + _mensaje;
            }
        }
Exemple #23
0
        /// <summary>
        /// save new customer
        /// </summary>
        /// <param name="newCustomer"></param>
        /// <returns></returns>
        public OperationResult SaveCustomer(RM00101_Customer newCustomer)
        {
            var operationResult = new OperationResult();

            var existingCustomer = _dynamicsContext.RM00101_Customer.FirstOrDefault(x => x.CUSTNMBR.Replace(" ", string.Empty) == newCustomer.CUSTNMBR);

            if (existingCustomer == null)
            {
                logger.Debug("Customer is being created...");

                string sCustomerDocument;
                string sXsdSchema;
                string sConnectionString;

                using (eConnectMethods e = new eConnectMethods())
                {
                    try
                    {
                        //// Create the vendor data file
                        //SerializeVendorObject("Vendor.xml", foundry);

                        //// Use an XML document to create a string representation of the customer
                        //XmlDocument xmldoc = new XmlDocument();
                        //xmldoc.Load("Vendor.xml");
                        //sCustomerDocument = xmldoc.OuterXml;

                        //// Specify the Microsoft Dynamics GP server and database in the connection string
                        //sConnectionString = @"data source=localhost;initial catalog=TWO;integrated security=SSPI;persist security info=False;packet size=4096";

                        //// Create an XML Document object for the schema
                        //XmlDocument XsdDoc = new XmlDocument();

                        //// Create a string representing the eConnect schema
                        //sXsdSchema = XsdDoc.OuterXml;

                        //// Pass in xsdSchema to validate against.
                        //e.CreateEntity(sConnectionString, sCustomerDocument);

                        // Instantiate a taUpdateCreateCustomerRcd XML node object
                        taUpdateCreateCustomerRcd customer = new taUpdateCreateCustomerRcd();

                        //Populate elements of the taUpdateCreateVendorRcd XML node object
                        customer.CUSTNMBR         = newCustomer.CUSTNMBR;
                        customer.UseCustomerClass = 1;
                        customer.CUSTCLAS         = "blah";
                        customer.UpdateIfExists   = 0;

                        // Instantiate a RMCustomerMasterType schema object
                        RMCustomerMasterType customertype = new RMCustomerMasterType();

                        // Populate the RMCustomerMasterType schema with the taUpdateCreateCustomerRcd XML node
                        customertype.taUpdateCreateCustomerRcd = customer;
                        RMCustomerMasterType[] customerMaster = { customertype };

                        // Instantiate an eConnectType schema object
                        eConnectType eConnect = new eConnectType();

                        // Instantiate a Memory Stream object
                        MemoryStream memoryStream = new MemoryStream();

                        // Create an XML serializer object
                        XmlSerializer serializer = new XmlSerializer(eConnect.GetType());

                        // Populate the eConnectType object with the PMVendorMasterType schema object
                        eConnect.RMCustomerMasterType = customerMaster;

                        // Serialize the eConnectType.
                        serializer.Serialize(memoryStream, eConnect);

                        // Reset the position of the memory stream to the start.
                        memoryStream.Position = 0;

                        // Create an XmlDocument from the serialized eConnectType in memory.
                        XmlDocument xmlDocument = new XmlDocument();
                        xmlDocument.Load(memoryStream);
                        memoryStream.Close();

                        // Call eConnect to process the XmlDocument.
                        e.CreateEntity(_dynamicsConnection, xmlDocument.OuterXml);

                        operationResult.Success = true;
                        operationResult.Message = "Success";
                    }
                    // The eConnectException class will catch eConnect business logic errors.
                    // display the error message on the console
                    catch (eConnectException exc)
                    {
                        Console.Write(exc.ToString());
                        operationResult.Success = false;
                        operationResult.Message = "Error";
                        logger.ErrorFormat("Error saving new customer: {0} ", exc.ToString());
                    }
                    // Catch any system error that might occurr.
                    // display the error message on the console
                    catch (System.Exception ex)
                    {
                        Console.Write(ex.ToString());
                        operationResult.Success = false;
                        operationResult.Message = "Error";
                        logger.ErrorFormat("Error saving new customer: {0} ", ex.ToString());
                    }
                    finally
                    {
                        // Call the Dispose method to release the resources
                        // of the eConnectMethds object
                        e.Dispose();
                    }
                } // end of using statement
            }
            else
            {
                operationResult.Success = false;
                operationResult.Message = "Duplicate Entry";
            }

            return(operationResult);
        }
Exemple #24
0
        /// <summary>
        /// save new receipt
        /// </summary>
        /// <param name="receipt"></param>
        /// <param name="receiptLines"></param>
        /// <returns></returns>
        public OperationResult SaveReceipt(POP10300_Receipt_Work receipt, List <POP10310> receiptLines)
        {
            var operationResult = new OperationResult();

            logger.Debug("Receipt is being created...");

            using (eConnectMethods e = new eConnectMethods())
            {
                try
                {
                    if (receiptLines != null && receiptLines.Count > 0)
                    {
                        taPopRcptLotInsert_ItemsTaPopRcptLotInsert[] lotItems = new taPopRcptLotInsert_ItemsTaPopRcptLotInsert[receiptLines.Count];

                        taPopRcptLineInsert_ItemsTaPopRcptLineInsert[] lineItems = new taPopRcptLineInsert_ItemsTaPopRcptLineInsert[receiptLines.Count];

                        var receiptLineNumber = 16384;
                        var lineNumber        = 0;

                        foreach (var receiptLine in receiptLines)
                        {
                            // Instantiate a taUpdateCreateItemRcd XML node object
                            taPopRcptLotInsert_ItemsTaPopRcptLotInsert receiptLotLine = new taPopRcptLotInsert_ItemsTaPopRcptLotInsert();

                            receiptLotLine.POPRCTNM  = receiptLine.POPRCTNM;
                            receiptLotLine.RCPTLNNM  = receiptLineNumber;
                            receiptLotLine.ITEMNMBR  = receiptLine.ITEMNMBR;
                            receiptLotLine.SERLTNUM  = receiptLine.SERLTNUM;
                            receiptLotLine.SERLTQTY  = receiptLine.QTYSHPPD;
                            receiptLotLine.CREATEBIN = 0;

                            lotItems[lineNumber] = receiptLotLine;

                            // Instantiate a taUpdateCreateItemRcd XML node object
                            taPopRcptLineInsert_ItemsTaPopRcptLineInsert receiptLineItem = new taPopRcptLineInsert_ItemsTaPopRcptLineInsert();

                            //Populate elements of the taUpdateCreateItemRcd XML node object
                            receiptLineItem.POPTYPE  = receiptLine.POPTYPE;
                            receiptLineItem.POPRCTNM = receiptLine.POPRCTNM;
                            receiptLineItem.RCPTLNNM = receiptLineNumber;
                            receiptLineItem.ITEMNMBR = receiptLine.ITEMNMBR;
                            receiptLineItem.VENDORID = receiptLine.VENDORID;
                            receiptLineItem.PONUMBER = receiptLine.PONUMBER;
                            receiptLineItem.VNDITNUM = receiptLine.VNDITNUM;
                            receiptLineItem.QTYSHPPD = receiptLine.QTYSHPPD;
                            receiptLineItem.AUTOCOST = 1;

                            lineItems[lineNumber] = receiptLineItem;

                            receiptLineNumber = receiptLineNumber * 2;

                            lineNumber++;
                        }

                        // Instantiate a taUpdateCreateItemRcd XML node object
                        taPopRcptHdrInsert receiptHeader = new taPopRcptHdrInsert();

                        //Populate elements of the taUpdateCreateItemRcd XML node object
                        receiptHeader.POPRCTNM    = receipt.POPRCTNM;
                        receiptHeader.POPTYPE     = receipt.POPTYPE;
                        receiptHeader.receiptdate = receipt.receiptdate;
                        receiptHeader.BACHNUMB    = receipt.BACHNUMB;
                        receiptHeader.VENDORID    = receipt.VENDORID;

                        // Instantiate a IVItemMasterType schema object
                        POPReceivingsType receipttype = new POPReceivingsType();

                        // Populate the IVItemMasterType schema with the taUpdateCreateItemRcd XML node
                        receipttype.taPopRcptLotInsert_Items  = lotItems;
                        receipttype.taPopRcptLineInsert_Items = lineItems;
                        receipttype.taPopRcptHdrInsert        = receiptHeader;
                        POPReceivingsType[] receiptEntry = { receipttype };

                        // Instantiate an eConnectType schema object
                        eConnectType eConnect = new eConnectType();

                        // Instantiate a Memory Stream object
                        MemoryStream memoryStream = new MemoryStream();

                        // Create an XML serializer object
                        XmlSerializer serializer = new XmlSerializer(eConnect.GetType());

                        // Populate the eConnectType object with the IVItemMasterType schema object
                        eConnect.POPReceivingsType = receiptEntry;

                        ///////////////////////////////////////////////////////////////////////////////

                        // Serialize the eConnectType.
                        serializer.Serialize(memoryStream, eConnect);

                        // Reset the position of the memory stream to the start.
                        memoryStream.Position = 0;

                        // Create an XmlDocument from the serialized eConnectType in memory.
                        XmlDocument xmlDocument = new XmlDocument();
                        xmlDocument.Load(memoryStream);
                        memoryStream.Close();

                        /////////////////////////////////////////////////////////////////////////////////

                        //string xmldocument;

                        //SerializeReceiptHeaderObject("C:\\receipt.xml", receipt, receiptLines);

                        ////Use an XML document to create a string representation of the customer
                        //XmlDocument xmldoc = new XmlDocument();
                        //xmldoc.Load("C:\\receipt.xml");
                        //xmldocument = xmldoc.OuterXml;

                        ////Call eConnect to process the xmldocument.
                        //e.CreateEntity(_dynamicsConnection, xmldocument);

                        //////////////////////////////////////////////////////////////////////////////////

                        // Call eConnect to process the XmlDocument.
                        e.CreateEntity(_dynamicsConnection, xmlDocument.OuterXml);

                        operationResult.Success = true;
                        operationResult.Message = "Success";
                    }
                    else
                    {
                        operationResult.Success = false;
                        operationResult.Message = "No items are attached to receive.";
                    }
                }
                // The eConnectException class will catch eConnect business logic errors.
                // display the error message on the console
                catch (eConnectException exc)
                {
                    Console.Write(exc.ToString());
                    operationResult.Success = false;
                    operationResult.Message = "Error";
                    logger.ErrorFormat("Error saving new receipt: {0} ", exc.ToString());
                }
                // Catch any system error that might occurr.
                // display the error message on the console
                catch (System.Exception ex)
                {
                    Console.Write(ex.ToString());
                    operationResult.Success = false;
                    operationResult.Message = "Error";
                    logger.ErrorFormat("Error saving new receipt: {0} ", ex.ToString());
                }
                finally
                {
                    // Call the Dispose method to release the resources
                    // of the eConnectMethds object
                    e.Dispose();
                }
            } // end of using statement

            return(operationResult);
        }
        public string CreateCustomerAddress(AccountAddress address)  // string path
        {
            try
            {
                // datos de la address
                taCreateCustomerAddress_ItemsTaCreateCustomerAddress add = new taCreateCustomerAddress_ItemsTaCreateCustomerAddress();
                
                add.CUSTNMBR = address.Account.AccountCode;
                add.ADRSCODE = address.ErpCode;
                add.ADDRESS1 = address.AddressLine1;
                add.ADDRESS2 = address.AddressLine2;
                add.ADDRESS3 = address.AddressLine3;
                add.CNTCPRSN = address.ContactPerson;
                add.PHNUMBR1 = address.Phone1;
                add.PHNUMBR2 = address.Phone2;
                add.PHNUMBR3 = address.Phone3;
                add.COUNTRY = address.Country;
                add.STATE = address.State;
                add.CITY = address.City;
                add.ZIPCODE = address.ZipCode;
                add.UpdateIfExists = 1;  //Update If Exists

                RMCustomerAddressType addType = new RMCustomerAddressType();
                addType.taCreateCustomerAddress_Items = new taCreateCustomerAddress_ItemsTaCreateCustomerAddress[] { add };

                RMCustomerAddressType[] arrAddTypes = { addType };

                //Create an eConnect XML document object and populate 
                eConnectType eConnect = new eConnectType();
                eConnect.RMCustomerAddressType = arrAddTypes;

                //Serialize the XML document to the file
                XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, eConnect);

                DynamicsGP_ec.SendData(writer.ToString()); 
                
                return address.Account.AccountCode;

            }
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("CreateCustomerAddress", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                throw;
            }

            
        }
Exemple #26
0
        /// <summary>
        /// Function to Retreive Data from GP Tables using eConnect, Return a string in XML Format
        /// </summary>
        /// <param name="DocumentType">Purchase_Order_Transaction, Sales_Order_Transaction</param>
        /// <param name="fromShadowTable">Direct From GP Tables or From EConnect Out</param>
        /// <param name="OutputType">0=List,1=Master document, 2=Complete document,3=Remove only</param>
        /// <param name="Action">Use this element when you request data from the shadow table. The value controls the type of data that is returned.
        /// 0=All documents
        /// 1=Insertions
        /// 2=Updates
        /// 3=Deletions
        /// 4=Returns all insertions and updates as separate documents for each item.
        /// 5=Combines all insertions and updates into one document for each item </param>
        /// <param name="WhereCondition">Custom Condition</param>
        /// <returns></returns>

        public static string RetreiveData(string DocumentType, bool fromShadowTable,
                int OutputType, int Action, string WhereCondition, bool RemoveShadow)
        {

            // Create a connection string to specify the Microsoft Dynamics GP server and database
            //string cnnString = "data source=(local);initial catalog=TWO;integrated security=SSPI;persist security info=False;packet size=4096";
            //string cnnString = "data source=WEBMASTERNT02;initial catalog=TWO;integrated security=SSPI;persist security info=False;packet size=4096";
            //string cnnString = "Data Source=192.168.1.4;initial catalog=TWO;integrated security=SSPI;persist security info=False;packet size=4096";
            //string cnnString = ConfigurationManager.AppSettings["GPCnnString"];

            try
            {
                // Create an eConnect document type object
                eConnectType myEConnectType = new eConnectType();
                // Create a RQeConnectOutType schema object
                RQeConnectOutType myReqType = new RQeConnectOutType();
                // Create an eConnectOut XML node object
                eConnectOut myeConnectOut = new eConnectOut();

                // Populate the eConnectOut XML node elements
                myeConnectOut.ACTION = Action;
                myeConnectOut.DOCTYPE = DocumentType;
                myeConnectOut.OUTPUTTYPE = OutputType;
                myeConnectOut.FORLIST = fromShadowTable ? 0 : 1;
                myeConnectOut.REMOVE = RemoveShadow ? 1 : 0;
                myeConnectOut.WhereClause = WhereCondition;


                // Add the eConnectOut XML node object to the RQeConnectOutType schema object
                myReqType.eConnectOut = myeConnectOut;

                // Add the RQeConnectOutType schema object to the eConnect document object
                RQeConnectOutType[] myReqOutType = { myReqType };
                myEConnectType.RQeConnectOutType = myReqOutType;

                // Serialize the eConnect document object to a memory stream
                MemoryStream myMemStream = new MemoryStream();
                XmlSerializer mySerializer = new XmlSerializer(myEConnectType.GetType());
                mySerializer.Serialize(myMemStream, myEConnectType);
                myMemStream.Position = 0;

                // Load the serialized eConnect document object into an XML document object
                XmlTextReader xmlreader = new XmlTextReader(myMemStream);
                XmlDocument myXmlDocument = new XmlDocument();
                myXmlDocument.Load(xmlreader);

                // Create an eConnectMethods object
                eConnectMethods requester = new eConnectMethods();

                //string outerXml = myXmlDocument.OuterXml;
                //int rem = 0x02;
                //outerXml = outerXml.Replace((char)rem, ' ');

                // Call the eConnect_Requester method of the eConnectMethods object to retrieve specified XML data
                return requester.eConnect_Requester(FactoryCompany.ErpConnection.CnnString, EnumTypes.ConnectionStringType.SqlClient, myXmlDocument.OuterXml); // outerXml);

            }

            catch (eConnectException ex)
            {
                // Dislay any errors that occur to the console
                throw new Exception(ex.Message);
            }
            catch (Exception e)
            {
                // Dislay any errors that occur to the console
                throw new Exception(e.Message);
            }

        }
        private void serializeSOPObject(string filename, Transaction assessment, string documentID, string defaultSiteID)
        {
            try
            {
                taSopLineIvcInsert_ItemsTaSopLineIvcInsert itemLine;

                taSopLineIvcInsert_ItemsTaSopLineIvcInsert[] lineItems =
                    new taSopLineIvcInsert_ItemsTaSopLineIvcInsert[assessment.Items.Count];


                int r = 0;
                //populate item lines
                foreach (Item item in assessment.Items)
                {
                    itemLine =
                        new taSopLineIvcInsert_ItemsTaSopLineIvcInsert();

                    //item pks
                    itemLine.SOPTYPE  = (short)assessment.TransactionType;
                    itemLine.CUSTNMBR = assessment.StudentID;
                    itemLine.SOPNUMBE = assessment.DocumentNumber;
                    itemLine.PRCLEVEL = assessment.PriceLevel; //20100527

                    itemLine.DOCID = documentID;
                    //item details
                    itemLine.ITEMNMBR = item.ItemNo;
                    itemLine.UOFM     = item.Uofm;
                    if (assessment.TransactionType == Transaction_Type.Drop)
                    {
                        itemLine.QUANTITY = item.Qty;
                        itemLine.QTYINSVC = item.Qty;
                    }
                    else if (assessment.TransactionType == Transaction_Type.Assessment)
                    {
                        itemLine.QUOTEQTYTOINV = item.Qty;
                    }
                    else if (assessment.TransactionType == Transaction_Type.Add)
                    {
                        itemLine.QUANTITY = item.Qty;
                    }
                    itemLine.ITEMDESC          = item.ItemDescription;
                    itemLine.UNITPRCE          = item.Unitprice;
                    itemLine.MRKDNPCTSpecified = true;
                    itemLine.MRKDNPCT          = item.MarkDown;

                    itemLine.XTNDPRCE = item.ExtendedPrice;
                    itemLine.LOCNCODE = defaultSiteID;
                    itemLine.DOCDATE  = assessment.DocumentDate.ToShortDateString();

                    //itemLine.UpdateIfExists = 1;
                    lineItems[r] = itemLine;
                    r           += 1;
                }
                //add items

                SOPTransactionType salesOrder = new SOPTransactionType();
                Array.Resize(ref salesOrder.taSopLineIvcInsert_Items, r);
                salesOrder.taSopLineIvcInsert_Items = lineItems;

                taSopHdrIvcInsert header = new taSopHdrIvcInsert();

                //populate header node
                header.SOPTYPE           = (short)assessment.TransactionType;
                header.SOPNUMBE          = assessment.DocumentNumber;
                header.DOCID             = documentID;
                header.PRCLEVEL          = assessment.PriceLevel; //20100527
                header.TRDISAMTSpecified = true;

                header.BACHNUMB = assessment.BatchID;
                header.LOCNCODE = defaultSiteID;
                header.CUSTNMBR = assessment.StudentID;
                header.CUSTNAME = assessment.StudentName;
                header.CURNCYID = assessment.CurrencyID;
                header.DOCDATE  = assessment.DocumentDate.ToShortDateString();
                if (assessment.TransactionType == Transaction_Type.Assessment)
                {
                    header.QUOEXPDA = assessment.ExpirationDate.ToShortDateString();
                    header.INVODATE = assessment.DocumentDate.ToShortDateString();
                }
                header.CMMTTEXT = assessment.Comments;
                header.SUBTOTAL = assessment.Subtotal;
                header.TRDISAMT = assessment.TotalDiscounts;
                header.MISCAMNT = assessment.InstallmentFee;
                header.DOCAMNT  = assessment.TotalAmount;
                header.USINGHEADERLEVELTAXES = 1;
                //header.DEFTAXSCHDS = 1;
                //header.UpdateExisting = 1;

                //add header

                salesOrder.taSopHdrIvcInsert = header;

                eConnectType eConnType = new eConnectType();
                Array.Resize(ref eConnType.SOPTransactionType, 1);
                eConnType.SOPTransactionType[0] = salesOrder;
                //serialization proper
                using (FileStream fs = new FileStream(filename, FileMode.Create))
                {
                    XmlTextWriter writer     = new XmlTextWriter(fs, new UTF8Encoding());
                    XmlSerializer serializer = new XmlSerializer(eConnType.GetType());
                    serializer.Serialize(writer, eConnType);
                    writer.Close();
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }
        public Boolean CreateLocationTransfer(Document trfDocument)
        {
            eConnectType eConnect;

            Console.WriteLine("In ErpConnect");

            try
            {
                taIVTransferLineInsert_ItemsTaIVTransferLineInsert[] docLines =
                    new taIVTransferLineInsert_ItemsTaIVTransferLineInsert[trfDocument.DocumentLines.Count];

                //Create an object that holds XML node object
                taIVTransferLineInsert_ItemsTaIVTransferLineInsert curLine;
                int i = 1;

                // Next consecutive for a Purchase Receipt
                foreach (DocumentLine dr in trfDocument.DocumentLines)
                {
                    curLine = new taIVTransferLineInsert_ItemsTaIVTransferLineInsert();

                    // Populate Lines            
                    curLine.ITEMNMBR = dr.Product.ProductCode;
                    curLine.IVDOCNBR = trfDocument.DocNumber;
                    curLine.LNSEQNBR = i;
                    curLine.TRXLOCTN = dr.Location.ErpCode; //ORIGEN
                    curLine.TRNSTLOC = dr.Location2.ErpCode; //DESTINO - ERP CODE
                    curLine.UOFM = dr.Unit.ErpCode;

                    /*
                    Override quantity flag; to use this element, inventory control must allow for adjustment overrides:
                    0=Reset TRXQTY with quantity available; 
                    1=Override quantity available and use TRXQTY 
                    Se debe configurar en el GP la Opcion en el Inventory Control 
                     */

                    curLine.OverrideQty = 1;
                    curLine.TRXQTY = Decimal.Parse(dr.Quantity.ToString());

                    docLines[i - 1] = curLine;
                    i++;
                }

                Console.WriteLine("Lines created");

                //Create a SOPTransactionType schema object and populate its taSopLineIvcInsert_Items poperty
                IVInventoryTransferType docType = new IVInventoryTransferType();
                docType.taIVTransferLineInsert_Items = docLines;

                //Create a taSopHdrIvcInsert XML node object
                taIVTransferHeaderInsert docHdr = new taIVTransferHeaderInsert();


                //Populate Header  
                //BATCH si hay notes, ahi se pone el BATCH
                if (string.IsNullOrEmpty(trfDocument.Notes))
                    docHdr.BACHNUMB = trfDocument.Location.ErpCode + "_" + GPBatchNumber.Inventory;
                else
                    docHdr.BACHNUMB = trfDocument.Notes;

                docHdr.DOCDATE = ((DateTime)trfDocument.Date1).ToString("yyyy-MM-dd"); //DateTime.Today.ToString();
                docHdr.IVDOCNBR = trfDocument.DocNumber; //TRF000X
                docHdr.POSTTOGL = 1;
                docHdr.USRDEFND4 = trfDocument.Comment;
                docHdr.USRDEFND5 = "";
                docType.taIVTransferHeaderInsert = docHdr;

                Console.WriteLine("Header created");

                IVInventoryTransferType[] docTypeArray = new IVInventoryTransferType[1];
                docTypeArray[0] = docType;

                //Create an eConnect XML document object and populate its docType property with
                //the docType schema object
                eConnect = new eConnectType();
                eConnect.IVInventoryTransferType = docTypeArray;

                //Serialize the XML document to the file
                XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, eConnect);

                DynamicsGP_ec.SendData(writer.ToString());
                Console.WriteLine("Send to GP");

                return true;
            }

            catch (Exception ex)
            {
                Console.WriteLine("ERROR: " + ex.Message);
                throw new Exception(WriteLog.GetTechMessage(ex));
                //ExceptionMngr.WriteEvent("CreateInventoryAdjustment:" + inventoryAdj.DocNumber, ListValues.EventType.Error, 
                //    ex, null, ListValues.ErrorCategory.ErpConnection);
                //return false;
            }
        }
        public Boolean CreateInventoryAdjustment(Document inventoryAdj, short adjType) 
            //adjType: Ajustment or Variance
        {

            eConnectType eConnect;

            try
            {
                taIVTransactionLineInsert_ItemsTaIVTransactionLineInsert[] docLines = 
                    new taIVTransactionLineInsert_ItemsTaIVTransactionLineInsert[inventoryAdj.DocumentLines.Count];

                //Create an object that holds XML node object
                taIVTransactionLineInsert_ItemsTaIVTransactionLineInsert curLine;
                int i = 1;
                int sign;

                // Next consecutive for a Purchase Receipt
                foreach (DocumentLine dr in inventoryAdj.DocumentLines)
                {
                    curLine = new taIVTransactionLineInsert_ItemsTaIVTransactionLineInsert();

                    // Populate Lines            
                    curLine.ITEMNMBR = dr.Product.ProductCode;
                    curLine.IVDOCNBR = inventoryAdj.DocNumber;
                    curLine.IVDOCTYP = (short)((adjType == GP_DocType.IV_Variance) ? GP_DocType.IV_Variance : GP_DocType.IV_Adjustment);
                    curLine.LNSEQNBR = i;
                    curLine.TRXLOCTN = inventoryAdj.Location.ErpCode;
                    curLine.UOFM = dr.Unit.ErpCode;
                    
                    /*
                    Override quantity flag; to use this element, inventory control must allow for adjustment overrides:
                    0=Reset TRXQTY with quantity available; 
                    1=Override quantity available and use TRXQTY 
                    Se debe configurar en el GP la Opcion en el Inventory Control 
                     */
                    curLine.OverrideQty = 1; 

                    sign = (dr.IsDebit == true) ? -1 : 1;
                    curLine.TRXQTY = sign * Decimal.Parse(dr.Quantity.ToString());
                   
                    docLines[i-1] = curLine;
                    i++;
                }

                //Create a SOPTransactionType schema object and populate its taSopLineIvcInsert_Items poperty
                IVInventoryTransactionType docType = new IVInventoryTransactionType();
                docType.taIVTransactionLineInsert_Items = docLines;

                //Create a taSopHdrIvcInsert XML node object
                taIVTransactionHeaderInsert docHdr = new taIVTransactionHeaderInsert();
                

                //Populate Header  
                //BATCH si hay notes, ahi se pone el BATCH
                if (string.IsNullOrEmpty(inventoryAdj.Notes))
                    docHdr.BACHNUMB = inventoryAdj.Location.ErpCode + "_" + GPBatchNumber.Inventory;
                else
                    docHdr.BACHNUMB = inventoryAdj.Notes;

                docHdr.DOCDATE = ((DateTime)inventoryAdj.Date1).ToString("yyyy-MM-dd"); //DateTime.Today.ToString();
                docHdr.IVDOCNBR = inventoryAdj.DocNumber; //IA00119

                //Determina si crea un adjustment o variance.
                docHdr.IVDOCTYP = (short)((adjType == GP_DocType.IV_Variance) ? GP_DocType.IV_Variance : GP_DocType.IV_Adjustment);
                
                
                docHdr.NOTETEXT = inventoryAdj.Comment;


                docType.taIVTransactionHeaderInsert = docHdr;

                IVInventoryTransactionType[] docTypeArray = new IVInventoryTransactionType[1];
                docTypeArray[0] = docType;

                //Create an eConnect XML document object and populate its docType property with
                //the docType schema object
                eConnect = new eConnectType();
                eConnect.IVInventoryTransactionType = docTypeArray;

                //Serialize the XML document to the file
                XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, eConnect);

                DynamicsGP_ec.SendData(writer.ToString());

                return true;
            }

            catch (Exception ex)
            {
                throw new Exception(WriteLog.GetTechMessage(ex));
                //ExceptionMngr.WriteEvent("CreateInventoryAdjustment:" + inventoryAdj.DocNumber, ListValues.EventType.Error, 
                //    ex, null, ListValues.ErrorCategory.ErpConnection);
                //return false;
            }

        }
        /// <summary>
        /// Con un Receiving Task generar el documento de Purchase Receipt a Generar
        /// </summary>
        /// <param name="recivingTask"></param>
        /// <returns></returns>
        public Boolean CreatePurchaseReceipt(Document receipt, IList<NodeTrace> traceList, bool costZero)
        {
            eConnectType eConnect;

            try
            {

                if (receipt.DocumentLines == null || receipt.DocumentLines.Count == 0)
                {
                    ExceptionMngr.WriteEvent("CreatePurchaseReceipt: No lines to process.", ListValues.EventType.Error, null, null,
                        ListValues.ErrorCategory.ErpConnection);

                    throw new Exception("CreatePurchaseReceipt: No lines to process.");
                }

                if (receipt.Location == null)
                {
                    ExceptionMngr.WriteEvent("CreatePurchaseReceipt: Document Location is missing.", ListValues.EventType.Error, null, null,
                        ListValues.ErrorCategory.ErpConnection);

                    throw new Exception("CreatePurchaseReceipt: Document Location is missing.");
                }

                taPopRcptLineInsert_ItemsTaPopRcptLineInsert[] docLines =
                    new taPopRcptLineInsert_ItemsTaPopRcptLineInsert[receipt.DocumentLines.Count];

                //Create an object that holds XML node object
                taPopRcptLineInsert_ItemsTaPopRcptLineInsert curLine;
                int i = 1;

                //For trak options
                IList<taPopRcptSerialInsert_ItemsTaPopRcptSerialInsert> serialTrack = new List<taPopRcptSerialInsert_ItemsTaPopRcptSerialInsert>();
                IList<taPopRcptLotInsert_ItemsTaPopRcptLotInsert> lotTrack = new List<taPopRcptLotInsert_ItemsTaPopRcptLotInsert>();


                // Next consecutive for a Purchase Receipt
                foreach (DocumentLine dr in receipt.DocumentLines)
                {
                    //Debe ser active, para garantizar que no es Misc, o service Item
                    if (dr.Product.Status.StatusID == EntityStatus.Active)
                    {

                        curLine = new taPopRcptLineInsert_ItemsTaPopRcptLineInsert();

                        //Validate Item/Vendor, GP requires that the Vendor has assigned the ItemNumber 
                        ValidateItemAndVendor(receipt.Vendor.AccountCode, dr.Product.ProductCode);

                        //Validate Item/Location, GP requires that the Location has assigned the ItemNumber 
                        ValidateItemAndLocation(receipt.Location.ErpCode, dr.Product.ProductCode);

                        // Populate Lines            
                        curLine.POPRCTNM = receipt.DocNumber;
                        curLine.POPTYPE = GP_DocType.PR_Shipment;
                        curLine.receiptdate = DateTime.Today.ToString("yyyy-MM-dd");
                        curLine.VENDORID = receipt.Vendor.AccountCode;

                        //Si va a Costo Zero el Costo debe ser enviado en el recibo como ZERO
                        if (costZero)
                        {
                            curLine.AUTOCOST = 0;
                            curLine.EXTDCOST = 0;
                            curLine.EXTDCOSTSpecified = true;
                            curLine.UNITCOST = 0;
                            curLine.UNITCOSTSpecified = true;                           
                        }
                        else
                            curLine.AUTOCOST = 1;                       
                        
                        curLine.ITEMNMBR = dr.Product.ProductCode;
                        curLine.VNDITNUM = dr.AccountItem;
                        curLine.LOCNCODE = dr.Location.ErpCode;
                        curLine.RCPTLNNM = i;
                        curLine.UOFM = dr.Unit.ErpCode;
                        curLine.QTYSHPPD = Decimal.Parse(dr.Quantity.ToString());


                        //Organizando los productos con Serial y Lotcode para cada linea del documento
                        if (dr.Product.ErpTrackOpt > 1 &&  dr.Product.ProductTrack != null)

                            foreach (ProductTrackRelation pt in dr.Product.ProductTrack)
                            {
                                if (pt.TrackOption.RowID == 1 && pt.DisplayName == null)  //Serial
                                    serialTrack = GetReceiptLineSerials(serialTrack, traceList.Where(f => f.PostingDocLineNumber == dr.LineNumber).ToList());

                                else if (pt.TrackOption.RowID == 2 && pt.DisplayName == null) //Lot Code
                                    lotTrack = GetReceiptLineLots(lotTrack, traceList.Where(f => f.PostingDocLineNumber == dr.LineNumber).ToList());
                            }


                        if (!string.IsNullOrEmpty(dr.LinkDocNumber))
                        {
                            curLine.PONUMBER = dr.LinkDocNumber;
                            curLine.POLNENUM = dr.LinkDocLineNumber;
                        }

                        docLines[i - 1] = curLine;
                        i++;
                    }
                }

                //Create a SOPTransactionType schema object and populate its taSopLineIvcInsert_Items poperty
                POPReceivingsType docType = new POPReceivingsType();

                //Adicionado Track Lists
                docType.taPopRcptLineInsert_Items = docLines;
                if (lotTrack.Count > 0)
                    docType.taPopRcptLotInsert_Items = lotTrack.ToArray();

                if (serialTrack.Count > 0)
                    docType.taPopRcptSerialInsert_Items = serialTrack.ToArray();

                //Create a taSopHdrIvcInsert XML node object

                taPopRcptHdrInsert docHdr = new taPopRcptHdrInsert();

                //Populate Header   
                docHdr.BACHNUMB = costZero ? "WMS_LANDING" : receipt.Location.ErpCode + "_" + GPBatchNumber.Receipt;

                docHdr.POPRCTNM = receipt.DocNumber;
                docHdr.POPTYPE = GP_DocType.PR_Shipment;
                docHdr.receiptdate = DateTime.Today.ToString("yyyy-MM-dd");
                docHdr.VENDORID = receipt.Vendor.AccountCode;

                //Define el Auto Cost
                docHdr.AUTOCOST = costZero ? 0 : 1;


                docHdr.NOTETEXT = "WMS DOC#: " + receipt.DocNumber;
                docHdr.VNDDOCNM = receipt.Reference;
                docHdr.DUEDATE = (receipt.Date5 == null) ? "" : receipt.Date5.Value.ToString("yyyy-MM-dd");

                docType.taPopRcptHdrInsert = docHdr;

                POPReceivingsType[] docTypeArray = new POPReceivingsType[1];
                docTypeArray[0] = docType;

                //Create an eConnect XML document object and populate its docType property with
                //the docType schema object
                eConnect = new eConnectType();
                eConnect.POPReceivingsType = docTypeArray;

                //Serialize the XML document to the file
                XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, eConnect);

                DynamicsGP_ec.SendData(writer.ToString());

                return true;
            }

            catch (Exception ex)
            {
                //ExceptionMngr.WriteEvent("CreatePurchaseReceipt: ", ListValues.EventType.Error, ex, null,
                    //ListValues.ErrorCategory.ErpConnection);

                throw new Exception(WriteLog.GetTechMessage(ex));
            }

        }
        private void CreateLocationItem(string locationCode, string itemNumber)
        {
            eConnectType eConnect;

            try
            {
                taItemSite_ItemsTaItemSite record = new taItemSite_ItemsTaItemSite();
                record.ITEMNMBR = itemNumber;
                record.LOCNCODE = locationCode;
                record.UpdateIfExists = 1;

                IVInventoryItemSiteType curType = new IVInventoryItemSiteType();
                curType.taItemSite_Items = new taItemSite_ItemsTaItemSite[] { record };              

                IVInventoryItemSiteType[] typeArray = new IVInventoryItemSiteType[] { curType };

                eConnect = new eConnectType();
                eConnect.IVInventoryItemSiteType = typeArray;

                //Serialize the XML document to the file
                XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, eConnect);

                DynamicsGP_ec.SendData(writer.ToString());
            }

            catch (Exception ex)
            {
                //ExceptionMngr.WriteEvent("CreateLocationItem: ", ListValues.EventType.Error, ex, null,
                    //ListValues.ErrorCategory.ErpConnection);

                throw new Exception("CreateLocationItem: " + ex.Message);
            }

        }
Exemple #32
0
        public VendorResponseDto ImportGPVendor(taUpdateCreateVendorRcd vendor)
        {
            var response = new VendorResponseDto();

            //var sw = new Stopwatch();
            //sw.Start();
            //decimal elapsedTime = 0;

            try
            {
                string clearValue = "~~~";
                string cdataValue = "<![CDATA[ ]]>";

                //Replace null or empty string properties with the clear data value
                vendor = Fn.ReplaceNullOrEmptyStringProperties(vendor, clearValue);

                var PMVendor = new PMVendorMasterType();
                PMVendor.taUpdateCreateVendorRcd = vendor;

                PMVendorMasterType[] PMVendorType = { PMVendor };

                eConnectType eConnect = new eConnectType();
                eConnect.PMVendorMasterType = PMVendorType;

                MemoryStream  memStream  = new MemoryStream();
                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());
                serializer.Serialize(memStream, eConnect);
                memStream.Position = 0;

                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(memStream);
                memStream.Close();

                string finalXML = xmlDocument.OuterXml;
                //After serialization, replace clearValue with the eConnect CDATA value to clear field values that should now be empty
                finalXML = finalXML.Replace(clearValue, cdataValue);

                string responseMessage = string.Empty;
                string errorMessage    = string.Empty;

                string vendorID   = vendor.VENDORID;
                string vendorName = vendor.VENDNAME;

                bool success = eConn.CreateEntity(ref responseMessage, finalXML, _config.Value.GPCompanyDB);

                response.Success   = success;
                response.ErrorCode = 0;

                if (success)
                {
                    response.Message = "Vendor " + vendorID + " imported successfully";
                }
                else
                {
                    errorMessage       = "Failed to import vendor " + vendorID + " - " + vendorName + ": " + responseMessage;
                    response.Message   = errorMessage;
                    response.ErrorCode = LoggingEvents.INSERT_VENDOR_FAILED;
                }

                //sw.Stop();
                //elapsedTime = Convert.ToDecimal(sw.ElapsedMilliseconds);
                //response.Elapsed = elapsedTime.ToString();

                //_logger.LogInformation(LoggingEvents.INSERT_VENDOR_COMPLETE, $"ImportVendor {vendorID} complete: " + response.Elapsed);

                return(response);
            }
            catch (Exception ex)
            {
                //sw.Stop();
                //elapsedTime = Convert.ToDecimal(sw.ElapsedMilliseconds);
                //response.Elapsed = elapsedTime.ToString();

                response.Success   = false;
                response.ErrorCode = LoggingEvents.INSERT_VENDOR_EXCEPTION;
                response.Message   = "An unexpected error occured in ImportGPVendor: " + ex.Message;
                return(response);
            }
        }
        public String CreatePurchaseOrder(Document document)
        {
            string Flag = "";



            if (document.DocumentLines == null || document.DocumentLines.Count <= 0)
                throw new Exception("Purchase order does not contains lines.");


            try
            {

            string POPNumber;
            //string DocPrefix = "SWEB"; //ej: SWEB o como se deban crear las ordenes
            //string Batch = "BATCH"; //Numero de Batch de las ordenes a Crear

            // Next consecutive for a P.O.
            Flag = "PO Sequence";

            GetNextDocNumbers nextPopNumber = new GetNextDocNumbers();
            POPNumber = nextPopNumber.GetNextPONumber(GetNextDocNumbers.IncrementDecrement.Increment,
                CurCompany.ErpConnection.CnnString);
 
                taPoLine_ItemsTaPoLine[] docLines = new taPoLine_ItemsTaPoLine[document.DocumentLines.Count];

                //Create an object that holds XML node object
                taPoLine_ItemsTaPoLine curLine;
                int i = 1;

                // Next consecutive for a Purchase Receipt
                foreach (DocumentLine dr in document.DocumentLines)
                {
                    //Debe ser active, para garantizar que no es Misc, o service Item
                    if (dr.Product.Status.StatusID == EntityStatus.Active)
                    {

                        curLine = new taPoLine_ItemsTaPoLine();

                        //Validate Item/Vendor, GP requires that the Vendor has assigned the ItemNumber 
                        ValidateItemAndVendor(document.Vendor.AccountCode, dr.Product.ProductCode);


                        //Validate Item/Location, GP requires that the Location has assigned the ItemNumber 
                        ValidateItemAndLocation(document.Location.ErpCode, dr.Product.ProductCode);

                        // Populate Lines      
                        Flag = "Line Info";
                        curLine.PONUMBER = POPNumber;
                        curLine.POTYPE = GP_DocType.PO_Standard;
                        curLine.VENDORID = document.Vendor.AccountCode;
                        curLine.QUANTITY = (decimal)dr.Quantity;
                        curLine.QUANTITYSpecified = true;
                        curLine.REQDATE = DateTime.Today.ToString("yyyy-MM-dd");
                        curLine.ITEMNMBR = dr.Product.ProductCode;
                        curLine.LOCNCODE = document.Location.ErpCode;
                        curLine.ORD = i;
                        curLine.UOFM = dr.Unit.ErpCode;
                        curLine.POLNESTA = 1; //NEW


                        docLines[i - 1] = curLine;
                        i++;
                    }
                }

                //Create a SOPTransactionType schema object and populate its taSopLineIvcInsert_Items poperty
                POPTransactionType docType = new POPTransactionType();

                //Adicionado Track Lists
                docType.taPoLine_Items = docLines;

                //Create a taSopHdrIvcInsert XML node object
                taPoHdr docHdr = new taPoHdr();

                //Populate Header   
                Flag = "Header Info";

                docHdr.PONUMBER = POPNumber;
                docHdr.POSTATUS = 1; //NEW
                docHdr.POTYPE = GP_DocType.PO_Standard;
                docHdr.REQDATE = DateTime.Today.ToString("yyyy-MM-dd");
                docHdr.VENDORID = document.Vendor.AccountCode;
                docHdr.NOTETEXT = document.Comment;

                docType.taPoHdr = docHdr;

                POPTransactionType[] docTypeArray = new POPTransactionType[1];
                docTypeArray[0] = docType;

                //Create an eConnect XML document object and populate its docType property with
                //the docType schema object
                Flag = "eConnect";

                eConnectType eConnect = new eConnectType();
                eConnect.POPTransactionType = docTypeArray;


                //Serialize the XML document to the file
                XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, eConnect);

                DynamicsGP_ec.SendData(writer.ToString());

                return POPNumber;
            }

            catch (Exception ex)
            {
                //ExceptionMngr.WriteEvent("CreatePurchaseOrder: ", ListValues.EventType.Error, ex, null,
                //    ListValues.ErrorCategory.ErpConnection);

                throw new Exception(Flag + ". " + WriteLog.GetTechMessage(ex));
            }
        }
        /// <summary>
        /// Crea el xml de una factura pop a partir de una fila de datos en una hoja excel.
        /// </summary>
        /// <param name="hojaXl">Hoja excel</param>
        /// <param name="filaXl">Fila de la hoja excel a procesar</param>
        public void integraFacturaPOP(ExcelWorksheet hojaXl, int filaXl, string sTimeStamp)
        {
            this.iError = 0;
            eConnectType       docEConnectIV  = new eConnectType();
            eConnectType       docEConnectPOP = new eConnectType();
            FacturaDeCompraPOP facturaPop     = new FacturaDeCompraPOP(_DatosConexionDB, 1);

            try
            {
                facturaPop.preparaFacturaPOP(hojaXl, filaXl, sTimeStamp, _Param);
                _filaNuevaFactura = facturaPop.iniciaNuevaFacturaEn;
                this.sMensajeDocu = "Fila: " + filaXl.ToString() + " Número Doc: " + facturaPop.facturaPopCa.VNDDOCNM + " Proveedor: " + facturaPop.facturaPopCa.VENDORID;

                //Ingresa el artículo - proveedor a GP
                if (facturaPop.iError == 0)
                {
                    docEConnectIV.IVVendorItemType = facturaPop.myVendorItemType;
                    this.serializa(docEConnectIV);
                    if (this.iError == 0)
                    {
                        this.integraEntityXml();
                    }
                }
                else
                {
                    this.sMensaje = facturaPop.sMensaje;
                    this.iError++;
                }

                //Ingresa la factura a GP
                if (this.iError == 0 && facturaPop.iError == 0)
                {
                    docEConnectPOP.POPReceivingsType = facturaPop.myFacturaPopType;
                    this.serializa(docEConnectPOP);
                    if (this.iError == 0)
                    {
                        this.integraTransactionXml();
                    }
                }

                //Si no hubo error y no es factura cogs, agrega datos para el servicio de impuestos
                FacturaDeCompraAdicionales adicionalesFactura = new FacturaDeCompraAdicionales(_DatosConexionDB, facturaPop);
                if (this.iError == 0 && facturaPop.iError == 0 && facturaPop.facturaPopCa.REFRENCE.Length > 1 && facturaPop.facturaPopCa.REFRENCE.Substring(0, 2) != "CO")
                {
                    adicionalesFactura.spEconn_nsacoa_gl00021(hojaXl, filaXl, _Param);
                    if (adicionalesFactura.iError != 0)
                    {
                        this.iError++;
                        this.sMensaje = adicionalesFactura.sMensaje;
                    }
                }

                //Si no hubo errores, agregar trip codes a los asientos contables
                if (this.iError == 0 && facturaPop.iError == 0)
                {
                    adicionalesFactura.spIfcAgregaDistribucionContable(facturaPop.facturaPopCa.POPRCTNM);
                    if (adicionalesFactura.iError != 0)
                    {
                        this.iError++;
                        this.sMensaje = adicionalesFactura.sMensaje;
                    }
                }
            }
            catch (eConnectException eConnErr)
            {
                sMensaje = "Excepción al preparar factura. " + eConnErr.Message + "[integraFacturaPOP]";
                iError++;
            }
            catch (ApplicationException ex)
            {
                sMensaje = "Excepción de aplicación. " + ex.Message + "[integraFacturaPOP]";
                iError++;
            }
            catch (Exception errorGral)
            {
                sMensaje = "Excepción desconocida. " + errorGral.Message + " [integraFacturaPOP]";
                iError++;
            }
        }
Exemple #35
0
        /// <summary>
        /// Function to Retreive Data from GP Tables using eConnect, Return a string in XML Format
        /// </summary>
        /// <param name="DocumentType">Purchase_Order_Transaction, Sales_Order_Transaction</param>
        /// <param name="fromShadowTable">Direct From GP Tables or From EConnect Out</param>
        /// <param name="OutputType">0=List,1=Master document, 2=Complete document,3=Remove only</param>
        /// <param name="Action">Use this element when you request data from the shadow table. The value controls the type of data that is returned.
        /// 0=All documents
        /// 1=Insertions
        /// 2=Updates
        /// 3=Deletions
        /// 4=Returns all insertions and updates as separate documents for each item.
        /// 5=Combines all insertions and updates into one document for each item </param>
        /// <param name="WhereCondition">Custom Condition</param>
        /// <returns></returns>

        public static string RetreiveData(string DocumentType, bool fromShadowTable,
                                          int OutputType, int Action, string WhereCondition, bool RemoveShadow)
        {
            // Create a connection string to specify the Microsoft Dynamics GP server and database
            //string cnnString = "data source=(local);initial catalog=TWO;integrated security=SSPI;persist security info=False;packet size=4096";
            //string cnnString = "data source=WEBMASTERNT02;initial catalog=TWO;integrated security=SSPI;persist security info=False;packet size=4096";
            //string cnnString = "Data Source=192.168.1.4;initial catalog=TWO;integrated security=SSPI;persist security info=False;packet size=4096";
            //string cnnString = ConfigurationManager.AppSettings["GPCnnString"];

            try
            {
                // Create an eConnect document type object
                eConnectType myEConnectType = new eConnectType();
                // Create a RQeConnectOutType schema object
                RQeConnectOutType myReqType = new RQeConnectOutType();
                // Create an eConnectOut XML node object
                eConnectOut myeConnectOut = new eConnectOut();

                // Populate the eConnectOut XML node elements
                myeConnectOut.ACTION      = Action;
                myeConnectOut.DOCTYPE     = DocumentType;
                myeConnectOut.OUTPUTTYPE  = OutputType;
                myeConnectOut.FORLIST     = fromShadowTable ? 0 : 1;
                myeConnectOut.REMOVE      = RemoveShadow ? 1 : 0;
                myeConnectOut.WhereClause = WhereCondition;


                // Add the eConnectOut XML node object to the RQeConnectOutType schema object
                myReqType.eConnectOut = myeConnectOut;

                // Add the RQeConnectOutType schema object to the eConnect document object
                RQeConnectOutType[] myReqOutType = { myReqType };
                myEConnectType.RQeConnectOutType = myReqOutType;

                // Serialize the eConnect document object to a memory stream
                MemoryStream  myMemStream  = new MemoryStream();
                XmlSerializer mySerializer = new XmlSerializer(myEConnectType.GetType());
                mySerializer.Serialize(myMemStream, myEConnectType);
                myMemStream.Position = 0;

                // Load the serialized eConnect document object into an XML document object
                XmlTextReader xmlreader     = new XmlTextReader(myMemStream);
                XmlDocument   myXmlDocument = new XmlDocument();
                myXmlDocument.Load(xmlreader);

                // Create an eConnectMethods object
                eConnectMethods requester = new eConnectMethods();

                //string outerXml = myXmlDocument.OuterXml;
                //int rem = 0x02;
                //outerXml = outerXml.Replace((char)rem, ' ');

                // Call the eConnect_Requester method of the eConnectMethods object to retrieve specified XML data
                return(requester.eConnect_Requester(FactoryCompany.ErpConnection.CnnString, EnumTypes.ConnectionStringType.SqlClient, myXmlDocument.OuterXml)); // outerXml);
            }

            catch (eConnectException ex)
            {
                // Dislay any errors that occur to the console
                throw new Exception(ex.Message);
            }
            catch (Exception e)
            {
                // Dislay any errors that occur to the console
                throw new Exception(e.Message);
            }
        }
        /// <summary>
        /// Crea el xml de una factura PM a partir de una fila de datos en una hoja excel. Si no existe el proveedor, lo crea.
        /// </summary>
        /// <param name="hojaXl">Hoja excel</param>
        /// <param name="filaXl">Fila de la hoja excel a procesar</param>
        public void integraFacturaPMyProveedor(ExcelWorksheet hojaXl, int filaXl, string sTimeStamp)
        {
            this.iError = 0;
            eConnectType      docEConnectPM   = new eConnectType();
            eConnectType      docEConnectProv = new eConnectType();
            FacturaDeCompraPM factura         = new FacturaDeCompraPM(_DatosConexionDB);
            Proveedor         proveedor       = new Proveedor(_DatosConexionDB);

            try
            {
                //Preparar nuevo proveedor en caso que sea factura y no exista en gp
                proveedor.preparaProveedorEconn(hojaXl, filaXl, _Param);
                if (proveedor.iError != 0)
                {
                    this.sMensaje = proveedor.sMensaje;
                    this.iError++;
                }

                //Prepara factura
                factura.preparaFacturaPM(hojaXl, filaXl, sTimeStamp, _Param);
                this._filaNuevaFactura = factura.iniciaNuevaFacturaEn;
                this.sMensajeDocu      = "Fila: " + filaXl.ToString() + " Número Doc: " + factura.facturaPm.DOCNUMBR + " Proveedor: " + factura.facturaPm.VENDORID + " Monto: " + factura.facturaPm.PRCHAMNT.ToString();

                if (this.iError == 0 && factura.iError != 0)
                {
                    this.sMensaje = factura.sMensaje;
                    this.iError++;
                }

                //Ingresa nuevo proveedor
                if (this.iError == 0 && proveedor.arrVendorType != null && proveedor.arrVendorType.Count() > 0)
                {
                    docEConnectProv.PMVendorMasterType = proveedor.arrVendorType;
                    this.serializa(docEConnectProv);

                    if (this.iError == 0)
                    {
                        this.integraEntityXml();
                    }
                }

                //Ingresa la factura a GP
                if (this.iError == 0)
                {
                    docEConnectPM.PMTransactionType = factura.arrFacturaPmType;
                    this.serializa(docEConnectPM);

                    //debug!!!!
                    //this.iError++;
                    //sMensaje = _sDocXml;

                    if (this.iError == 0)
                    {
                        this.integraTransactionXml();
                    }
                }

                //Si es factura agrega datos para el servicio de impuestos
                if (this.iError == 0 && factura.facturaPm.DOCTYPE == 1)
                {
                    FacturaDeCompraAdicionales adicionalesFactura = new FacturaDeCompraAdicionales(_DatosConexionDB, factura);
                    adicionalesFactura.spIfc_AgregaTII_4001();
                    if (adicionalesFactura.iError != 0)
                    {
                        this.sMensaje = adicionalesFactura.sMensaje;
                        this.iError++;
                    }
                }
            }
            catch (eConnectException eConnErr)
            {
                sMensaje = "Excepción al preparar factura. " + eConnErr.Message + "[integraFacturaPMyProveedor.integraFacturaPM]";
                iError++;
            }
            catch (ApplicationException ex)
            {
                sMensaje = "Excepción de aplicación. " + ex.Message + "[integraFacturaPMyProveedor.integraFacturaPM]";
                iError++;
            }
            catch (Exception errorGral)
            {
                sMensaje = "Excepción desconocida. " + errorGral.Message + " [integraFacturaPMyProveedor.integraFacturaPM]";
                iError++;
            }
        }
Exemple #37
0
        /// <summary>
        /// serialize recipt
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="receipt"></param>
        /// <param name="receiptLines"></param>
        private static void SerializeReceiptObject(string filename, POP10300_Receipt_Work receipt, List <POP10310> receiptLines)
        {
            try
            {
                // Instantiate an eConnectType schema object
                eConnectType eConnect = new eConnectType();

                taPopRcptLineInsert_ItemsTaPopRcptLineInsert[] lineItems = new taPopRcptLineInsert_ItemsTaPopRcptLineInsert[receiptLines.Count];

                taPopRcptLotInsert_ItemsTaPopRcptLotInsert[] lotItems = new taPopRcptLotInsert_ItemsTaPopRcptLotInsert[receiptLines.Count];

                var receiptLineNumber = 16384;
                var lineNumber        = 0;

                foreach (var receiptLine in receiptLines)
                {
                    // Instantiate a taUpdateCreateItemRcd XML node object
                    taPopRcptLotInsert_ItemsTaPopRcptLotInsert receiptLotLine = new taPopRcptLotInsert_ItemsTaPopRcptLotInsert();

                    receiptLotLine.POPRCTNM  = receiptLine.POPRCTNM;
                    receiptLotLine.RCPTLNNM  = receiptLineNumber;
                    receiptLotLine.ITEMNMBR  = receiptLine.ITEMNMBR;
                    receiptLotLine.SERLTNUM  = receiptLine.SERLTNUM;
                    receiptLotLine.SERLTQTY  = receiptLine.QTYSHPPD;
                    receiptLotLine.CREATEBIN = 0;

                    lotItems[lineNumber] = receiptLotLine;

                    // Instantiate a taUpdateCreateItemRcd XML node object
                    taPopRcptLineInsert_ItemsTaPopRcptLineInsert receiptLineItem = new taPopRcptLineInsert_ItemsTaPopRcptLineInsert();

                    //Populate elements of the taUpdateCreateItemRcd XML node object
                    receiptLineItem.POPTYPE  = receiptLine.POPTYPE;
                    receiptLineItem.POPRCTNM = receiptLine.POPRCTNM;
                    receiptLineItem.RCPTLNNM = receiptLineNumber;
                    receiptLineItem.ITEMNMBR = receiptLine.ITEMNMBR;
                    receiptLineItem.VENDORID = receiptLine.VENDORID;
                    receiptLineItem.PONUMBER = receiptLine.PONUMBER;
                    receiptLineItem.VNDITNUM = receiptLine.VNDITNUM;
                    receiptLineItem.QTYSHPPD = receiptLine.QTYSHPPD;
                    receiptLineItem.AUTOCOST = 1;

                    lineItems[lineNumber] = receiptLineItem;

                    receiptLineNumber = receiptLineNumber * 2;

                    lineNumber++;
                }

                // Instantiate a taUpdateCreateItemRcd XML node object
                taPopRcptHdrInsert receiptHeader = new taPopRcptHdrInsert();

                //Populate elements of the taUpdateCreateItemRcd XML node object
                receiptHeader.POPRCTNM    = receipt.POPRCTNM;
                receiptHeader.POPTYPE     = receipt.POPTYPE;
                receiptHeader.receiptdate = receipt.receiptdate;
                receiptHeader.BACHNUMB    = receipt.BACHNUMB;
                receiptHeader.VENDORID    = receipt.VENDORID;

                // Instantiate a IVItemMasterType schema object
                POPReceivingsType receipttype = new POPReceivingsType();

                // Populate the IVItemMasterType schema with the taUpdateCreateItemRcd XML node
                receipttype.taPopRcptLotInsert_Items  = lotItems;
                receipttype.taPopRcptLineInsert_Items = lineItems;
                receipttype.taPopRcptHdrInsert        = receiptHeader;
                POPReceivingsType[] receiptEntry = { receipttype };

                // Instantiate a Memory Stream object
                MemoryStream memoryStream = new MemoryStream();

                // Create an XML serializer object
                XmlSerializer serializer = new XmlSerializer(eConnect.GetType());

                // Populate the eConnectType object with the IVItemMasterType schema object
                eConnect.POPReceivingsType = receiptEntry;

                // Create objects to create file and write the customer XML to the file
                FileStream    fs     = new FileStream(filename, FileMode.Create);
                XmlTextWriter writer = new XmlTextWriter(fs, new UTF8Encoding());

                // Serialize the eConnectType object to a file using the XmlTextWriter.
                serializer.Serialize(writer, eConnect);
                writer.Close();
            }
            // catch any errors that occur and display them to the console
            catch (System.Exception ex)
            {
                Console.Write(ex.ToString());
            }
        }
        /// <summary>
        /// Crea el xml de una factura PM a partir de una fila de datos en una hoja excel.
        /// </summary>
        /// <param name="hojaXl">Hoja excel</param>
        /// <param name="filaXl">Fila de la hoja excel a procesar</param>
        public void integraFacturaPM(ExcelWorksheet hojaXl, int filaXl, string sTimeStamp)
        {
            this.iError = 0;
            eConnectType      docEConnectPM   = new eConnectType();
            eConnectType      docEConnectProv = new eConnectType();
            FacturaDeCompraPM factura         = new FacturaDeCompraPM(_DatosConexionDB);
            Proveedor         proveedor       = new Proveedor(_DatosConexionDB);

            try
            {
                //Prepara factura
                factura.preparaFacturaPM(hojaXl, filaXl, sTimeStamp, _Param);
                this._filaNuevaFactura = factura.iniciaNuevaFacturaEn;
                this.sMensajeDocu      = "Fila: " + filaXl.ToString() + " Número Doc: " + factura.facturaPm.DOCNUMBR + " Proveedor: " + factura.facturaPm.VENDORID + " Monto: " + factura.facturaPm.PRCHAMNT.ToString();

                if (this.iError == 0 && factura.iError != 0)
                {
                    this.sMensaje = factura.sMensaje;
                    this.iError++;
                }

                //Ingresa la factura a GP
                if (this.iError == 0)
                {
                    docEConnectPM.PMTransactionType = factura.arrFacturaPmType;
                    this.serializa(docEConnectPM);

                    //debug!!!!
                    //this.iError++;
                    //sMensaje = _sDocXml;

                    if (this.iError == 0)
                    {
                        this.integraTransactionXml();
                    }
                }

                if (_Param.FacturaPmLOCALIZACION.Equals("ARG"))
                {
                    //Si es factura agrega datos para el servicio de impuestos
                    FacturaDeCompraAdicionales adicionalesFactura = new FacturaDeCompraAdicionales(_DatosConexionDB, factura);
                    if (this.iError == 0 && factura.facturaPm.DOCTYPE == 1)
                    {
                        adicionalesFactura.spIfc_Nfret_gl10030();
                        adicionalesFactura.spIfc_awli_pm00400();
                    }
                }
            }
            catch (eConnectException eConnErr)
            {
                sMensaje = "Excepción al preparar factura. " + eConnErr.Message + "[IntegraComprasGP.integraFacturaPM]";
                iError++;
            }
            catch (ApplicationException ex)
            {
                sMensaje = "Excepción de aplicación. " + ex.Message + "[IntegraComprasGP.integraFacturaPM]";
                iError++;
            }
            catch (Exception errorGral)
            {
                sMensaje = "Excepción. " + errorGral.Message + " [IntegraComprasGP.integraFacturaPM]";
                iError++;
            }
        }
        public String CreateCustomer(Account customer)
        {
            try {
                // datos de la address
                taUpdateCreateCustomerRcd record = new taUpdateCreateCustomerRcd
                {
                    CUSTNAME = customer.Name,
                    CUSTNMBR = customer.AccountCode,
                    //CNTCPRSN = customer.ContactPerson,
                    //PHNUMBR1 = customer.Phone,
                    USERDEF1 = customer.UserDefine1,
                    USERDEF2 = customer.UserDefine2,
                    USRDEFND3 = customer.UserDefine3,
                    COMMENT1 = customer.UserDefine1,
                    UpdateIfExists = 0                    
                };

                RMCustomerMasterType eType = new RMCustomerMasterType();
                eType.taUpdateCreateCustomerRcd = record;

                RMCustomerMasterType[] arrCustTypes = { eType };

                //Create an eConnect XML document object and populate 
                eConnectType eConnect = new eConnectType();
                eConnect.RMCustomerMasterType = arrCustTypes;

                //Serialize the XML document to the file
                XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, eConnect);

                DynamicsGP_ec.SendData(writer.ToString());
                
                if (customer.AccountAddresses != null)
                    foreach (AccountAddress address in customer.AccountAddresses)
                        CreateCustomerAddress(address);


                return customer.AccountCode;

            }

            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("CreateCustomer", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                throw;
            }
        }
        private int CreateSalesOrderLine(DocumentLine docLine, bool isMerged)
        {
            string flag = "Data Definition";

            try
            {
                Command.Connection = new SqlConnection(CurCompany.ErpConnection.CnnString);

                //Create an object that holds XML node object
                taSopLineIvcInsert_ItemsTaSopLineIvcInsert curLine = new taSopLineIvcInsert_ItemsTaSopLineIvcInsert();


                string document = (isMerged) ? docLine.LinkDocNumber : docLine.Document.DocNumber;
                string note = docLine.Note == null ? "" : docLine.Note;

                curLine.SOPTYPE = GP_DocType.SO_Order;
                curLine.CUSTNMBR = docLine.Document.Customer.AccountCode;
                curLine.DOCDATE = ((DateTime)docLine.Document.Date1).ToString("yyyy-MM-dd");
                curLine.SOPNUMBE = document;

                flag = "Item Definition";
                curLine.ITEMDESC = string.IsNullOrEmpty(docLine.LineDescription) ? docLine.Product.Name : docLine.LineDescription;
                curLine.ITEMNMBR = docLine.Product.ProductCode;
                curLine.QUANTITY = (decimal)docLine.Quantity;                
                curLine.UOFM = docLine.Unit.ErpCode;

                curLine.QTYCANCE = (decimal)docLine.QtyCancel;
                curLine.QTYTBAOR = (decimal)docLine.QtyBackOrder;
                curLine.UpdateIfExists = 1;
                //curLine.LNITMSEQ = 0;
                curLine.CMMTTEXT = note;
                curLine.ALLOCATE = 0;
                curLine.LOCNCODE = docLine.Location.ErpCode;

                string docID = ReturnScalar("SELECT DOCID FROM SOP10100 WHERE SOPNUMBE='" + document + "' AND SOPTYPE=2", "", Command.Connection);
                curLine.DOCID = docID;
                

                string xGuid = Guid.NewGuid().ToString();
                curLine.CNTCPRSN = xGuid;

                flag = "eConnect Definition";

                taSopLineIvcInsert_ItemsTaSopLineIvcInsert[] erpLines =
                    new taSopLineIvcInsert_ItemsTaSopLineIvcInsert[] { curLine };


                //Create a SOPTransactionType schema object and populate its taSopLineIvcInsert_Items poperty
                SOPTransactionType salesOrder = new SOPTransactionType();
                salesOrder.taSopLineIvcInsert_Items = erpLines;


                //SALES ORDER HEADER

                //Create a taSopHdrIvcInsert XML node object
                taSopHdrIvcInsert salesHdr = new taSopHdrIvcInsert();

                //Populate the properties of the taSopHdrIvcInsert XML node object           

                salesHdr.SOPTYPE = 2;
                salesHdr.SOPNUMBE = document;
                salesHdr.DOCID = ReturnScalar("SELECT DOCID FROM SOP10100 WHERE SOPNUMBE='" + document + "' AND SOPTYPE=2", "", Command.Connection);
                salesHdr.BACHNUMB = ReturnScalar("SELECT BACHNUMB FROM SOP10100 WHERE SOPNUMBE='" + document + "' AND SOPTYPE=2", "", Command.Connection); // "B2BSO";
                salesHdr.LOCNCODE = docLine.Document.Location.ErpCode;
                salesHdr.DOCDATE = ((DateTime)docLine.Document.Date1).ToString("yyyy-MM-dd");
                salesHdr.UpdateExisting = 1;
                salesHdr.CUSTNMBR = docLine.Document.Customer.AccountCode;
                salesHdr.CSTPONBR = docLine.Document.CustPONumber;                

                salesOrder.taSopHdrIvcInsert = salesHdr;

                //SALES ORDER HEADER


                SOPTransactionType[] salesOrderArray = new SOPTransactionType[1];
                salesOrderArray[0] = salesOrder;

                //Create an eConnect XML document object and populate its SOPTransactionType property with
                //the SOPTransactionType schema object
                eConnectType eConnect = new eConnectType();
                eConnect.SOPTransactionType = salesOrderArray;

                //Serialize the XML document to the file
                XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, eConnect);

                DynamicsGP_ec.SendData(writer.ToString());

                //Obterne el line ID creado
                flag = "Line Number";

                string  newLine;
                newLine = ReturnScalar("SELECT MAX(LNITMSEQ) FROM SOP10200 WHERE SOPNUMBE='" + document + "' AND CNTCPRSN ='" + xGuid + "'", "", Command.Connection);
                return int.Parse(newLine);


            }
            catch (Exception ex)
            {
                throw new Exception(flag + ". " +WriteLog.GetTechMessage(ex));
            }

        }
        public String CreateSalesOrder(Document document, string docPrefix, string batch)
        {

            if (document.DocumentLines == null || document.DocumentLines.Count <= 0)
                throw new Exception("Sales order does not contains lines.");

            string SOPNumber;
            //string DocPrefix = "SWEB"; //ej: SWEB o como se deban crear las ordenes
            //string Batch = "BATCH"; //Numero de Batch de las ordenes a Crear

            try
            {

                taSopLineIvcInsert_ItemsTaSopLineIvcInsert[] salesLine = new taSopLineIvcInsert_ItemsTaSopLineIvcInsert[document.DocumentLines.Count];
                //Create an object that holds XML node object
                taSopLineIvcInsert_ItemsTaSopLineIvcInsert LineItem; // = new taSopLineIvcInsert_ItemsTaSopLineIvcInsert();
                int lineSeq = 0;
                Decimal subTotal = 0;

                // Next consecutive for a S.O.
                GetSopNumber mySopNumber = new GetSopNumber();
                SOPNumber = mySopNumber.GetNextSopNumber(2, docPrefix, CurCompany.ErpConnection.CnnString);


                Console.WriteLine("1");

                foreach (DocumentLine dl in document.DocumentLines)
                {
                    LineItem = new taSopLineIvcInsert_ItemsTaSopLineIvcInsert();

                    // Populate            
                    LineItem.CUSTNMBR = dl.Document.Customer.AccountCode;
                    LineItem.SOPNUMBE = SOPNumber;
                    LineItem.SOPTYPE = 2;
                    LineItem.DOCID = docPrefix;   // SWEB   STDORD
                    LineItem.ITEMNMBR = dl.Product.ProductCode;
                    LineItem.UOFM = dl.Unit.ErpCode;
                    LineItem.UNITPRCE = (decimal)dl.UnitPrice;
                    LineItem.XTNDPRCE = (decimal)dl.ExtendedPrice;
                    LineItem.LOCNCODE = document.Location.ErpCode;
                    LineItem.DOCDATE = DateTime.Now.ToShortDateString();
                    LineItem.PRCLEVEL = "STANDARD";

                    // quantities
                    LineItem.QUANTITY = (decimal)dl.Quantity;

                    salesLine[lineSeq++] = LineItem;
                    subTotal += (decimal)dl.ExtendedPrice;
                }


                //Create a SOPTransactionType schema object and populate its taSopLineIvcInsert_Items poperty
                SOPTransactionType salesOrder = new SOPTransactionType();
                salesOrder.taSopLineIvcInsert_Items = salesLine;

                //Create a taSopHdrIvcInsert XML node object
                taSopHdrIvcInsert salesHdr = new taSopHdrIvcInsert();

                //Populate the properties of the taSopHdrIvcInsert XML node object           

                salesHdr.SOPTYPE = 2;
                salesHdr.SOPNUMBE = SOPNumber;
                salesHdr.DOCID = docPrefix;
                salesHdr.BACHNUMB = batch; // "B2BSO";
                salesHdr.LOCNCODE = document.Location.ErpCode;
                salesHdr.DOCDATE = DateTime.Now.ToShortDateString();
                salesHdr.SUBTOTAL = subTotal;
                salesHdr.DOCAMNT = subTotal;
                
                salesHdr.CUSTNMBR = document.Customer.AccountCode;
                salesHdr.CUSTNAME = document.Customer.Name;

                //if (document.ErpMaster > 0)
                    //salesHdr.MSTRNUMB = document.ErpMaster;

                //BILLING
                try { salesHdr.PRBTADCD = document.Customer.AccountAddresses[0].ErpCode; }
                catch
                {
                    salesHdr.PRBTADCD = document.DocumentAddresses
                        .Where(f => f.AddressType == AddressType.Billing).First().ErpCode;
                }

                //SHIPPING
                try { salesHdr.PRSTADCD = document.Customer.AccountAddresses[0].ErpCode; }
                catch
                {
                    salesHdr.PRBTADCD = document.DocumentAddresses
                        .Where(f => f.AddressType == AddressType.Shipping).First().ErpCode;
                }

                salesHdr.CSTPONBR = document.CustPONumber;

                salesOrder.taSopHdrIvcInsert = salesHdr;

                SOPTransactionType[] salesOrderArray = new SOPTransactionType[1];
                salesOrderArray[0] = salesOrder;

                //Create an eConnect XML document object and populate its SOPTransactionType property with
                //the SOPTransactionType schema object
                eConnectType eConnect = new eConnectType();
                eConnect.SOPTransactionType = salesOrderArray;

                //Serialize the XML document to the file
                XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, eConnect);

                DynamicsGP_ec.SendData(writer.ToString());

                //mySopNumber.Dispose();

                return SOPNumber;

            }
            
            catch (Exception ex)
            {
                ExceptionMngr.WriteEvent("CreateSalesOrder", ListValues.EventType.Error, ex, null, ListValues.ErrorCategory.ErpConnection);
                throw;
            }
        }
        private int RemoveSalesOrderLine(DocumentLine docLine, bool isMerged)
        {
            try {

                //Create an object that holds XML node object
                taSopLineDelete curLine = new taSopLineDelete();

                // Populate Lines            
                if (docLine.Document.DocType.DocTypeID == SDocType.SalesOrder)
                    curLine.SOPTYPE = GP_DocType.SO_Order;
                else if (docLine.Document.DocType.DocTypeID == SDocType.BackOrder)
                    curLine.SOPTYPE = GP_DocType.SO_BackOrder;


                curLine.ITEMNMBR = docLine.Product.ProductCode;
                curLine.DeleteType = 1;

                curLine.SOPNUMBE = docLine.Document.DocNumber;
                curLine.LNITMSEQ = docLine.LineNumber;


                //if (isMerged)
                //{
                //    curLine.SOPNUMBE = docLine.Document.DocNumber;
                //    curLine.LNITMSEQ = docLine.LineNumber;
                //}
                //else
                //{
                //    curLine.SOPNUMBE = docLine.Document.DocNumber;
                //    curLine.LNITMSEQ = docLine.LineNumber;
                //}


                //Create a SOPTransactionType schema object and populate its taSopLineIvcInsert_Items poperty
                SOPDeleteLineType record = new SOPDeleteLineType();
                record.taSopLineDelete = curLine;

                SOPDeleteLineType[] rArray = new SOPDeleteLineType[]{ record };

                //Create an eConnect XML document object and populate its SOPTransactionType property with
                //the SOPTransactionType schema object
                eConnectType eConnect = new eConnectType();
                eConnect.SOPDeleteLineType = rArray;

                //Serialize the XML document to the file
                XmlSerializer serializer = new XmlSerializer(typeof(eConnectType));
                StringWriter writer = new StringWriter();
                serializer.Serialize(writer, eConnect);

                DynamicsGP_ec.SendData(writer.ToString());

                return 0;
            }
            catch (Exception ex)
            {
                throw new Exception(WriteLog.GetTechMessage(ex));
            }

        }
Exemple #43
0
        /// <summary>
        /// save new inventory transaction
        /// </summary>
        /// <param name="transaction"></param>
        /// <param name="transactionLines"></param>
        /// <returns></returns>
        public OperationResult SaveInventoryTransaction(IV10000_IventoryTransaction_Work transaction, List <IV10000_IventoryTransaction_Work> transactionLines)
        {
            var operationResult = new OperationResult();

            logger.Debug("Receipt is being created...");

            using (eConnectMethods e = new eConnectMethods())
            {
                try
                {
                    if (transactionLines != null && transactionLines.Count > 0)
                    {
                        taIVTransactionLotInsert_ItemsTaIVTransactionLotInsert[] lotItems = new taIVTransactionLotInsert_ItemsTaIVTransactionLotInsert[transactionLines.Count];

                        taIVTransactionLineInsert_ItemsTaIVTransactionLineInsert[] lineItems = new taIVTransactionLineInsert_ItemsTaIVTransactionLineInsert[transactionLines.Count];

                        var transactionLineNumber = 16384;
                        var lineNumber            = 0;

                        foreach (var transactionLine in transactionLines)
                        {
                            //// Instantiate a taUpdateCreateItemRcd XML node object
                            taIVTransactionLotInsert_ItemsTaIVTransactionLotInsert transactionLotItem = new taIVTransactionLotInsert_ItemsTaIVTransactionLotInsert();

                            //Populate elements of the taUpdateCreateItemRcd XML node object
                            transactionLotItem.IVDOCNBR = transactionLine.IVDOCNBR;
                            transactionLotItem.IVDOCTYP = transactionLine.IVDOCTYP;
                            transactionLotItem.LOTNUMBR = transactionLine.LOTNUMBR;
                            transactionLotItem.ITEMNMBR = transactionLine.ITEMNMBR;
                            transactionLotItem.SERLTQTY = transactionLine.TRXQTY;
                            transactionLotItem.LOCNCODE = transactionLine.TRXLOCTN;
                            //transactionLotItem.EXPNDATE = transactionLine.EXPNDATE;
                            //transactionLotItem.DATERECD = transactionLine.DATERECD;

                            lotItems[lineNumber] = transactionLotItem;

                            // Instantiate a taUpdateCreateItemRcd XML node object
                            taIVTransactionLineInsert_ItemsTaIVTransactionLineInsert transactionLineItem = new taIVTransactionLineInsert_ItemsTaIVTransactionLineInsert();

                            //Populate elements of the taUpdateCreateItemRcd XML node object
                            transactionLineItem.IVDOCNBR = transactionLine.IVDOCNBR;
                            transactionLineItem.IVDOCTYP = transactionLine.IVDOCTYP;
                            //transactionLineItem.LNSEQNBR = transactionLine.LNSEQNBR;
                            transactionLineItem.ITEMNMBR = transactionLine.ITEMNMBR;
                            transactionLineItem.TRXLOCTN = transactionLine.TRXLOCTN;
                            transactionLineItem.TRXQTY   = transactionLine.TRXQTY;
                            //transactionLineItem.Reason_Code = transactionLine.Reason_Code;

                            lineItems[lineNumber] = transactionLineItem;

                            transactionLineNumber = transactionLineNumber * 2;

                            lineNumber++;
                        }

                        // Instantiate a taUpdateCreateItemRcd XML node object
                        taIVTransactionHeaderInsert transactionHeader = new taIVTransactionHeaderInsert();

                        //Populate elements of the taUpdateCreateItemRcd XML node object
                        transactionHeader.BACHNUMB = transaction.BACHNUMB;
                        transactionHeader.IVDOCNBR = transaction.IVDOCNBR;
                        transactionHeader.IVDOCTYP = transaction.IVDOCTYP;
                        transactionHeader.DOCDATE  = transaction.DOCDATE;

                        // Instantiate a IVItemMasterType schema object
                        IVInventoryTransactionType transactiontype = new IVInventoryTransactionType();

                        // Populate the IVItemMasterType schema with the taUpdateCreateItemRcd XML node
                        transactiontype.taIVTransactionLotInsert_Items  = lotItems;
                        transactiontype.taIVTransactionLineInsert_Items = lineItems;
                        transactiontype.taIVTransactionHeaderInsert     = transactionHeader;
                        IVInventoryTransactionType[] transactionEntry = { transactiontype };

                        // Instantiate an eConnectType schema object
                        eConnectType eConnect = new eConnectType();

                        // Instantiate a Memory Stream object
                        MemoryStream memoryStream = new MemoryStream();

                        // Create an XML serializer object
                        XmlSerializer serializer = new XmlSerializer(eConnect.GetType());

                        // Populate the eConnectType object with the IVItemMasterType schema object
                        eConnect.IVInventoryTransactionType = transactionEntry;

                        ///////////////////////////////////////////////////////////////////////////////

                        // Serialize the eConnectType.
                        serializer.Serialize(memoryStream, eConnect);

                        // Reset the position of the memory stream to the start.
                        memoryStream.Position = 0;

                        // Create an XmlDocument from the serialized eConnectType in memory.
                        XmlDocument xmlDocument = new XmlDocument();
                        xmlDocument.Load(memoryStream);
                        memoryStream.Close();

                        // Call eConnect to process the XmlDocument.
                        e.CreateEntity(_dynamicsConnection, xmlDocument.OuterXml);

                        /////////////////////////////////////////////////////////////////////////////////

                        //string xmldocument;

                        //SerializeTransactionObject("C:\\inventoryTransaction.xml", transaction, transactionLines);

                        ////Use an XML document to create a string representation of the customer
                        //XmlDocument xmldoc = new XmlDocument();
                        //xmldoc.Load("C:\\inventoryTransaction.xml");
                        //xmldocument = xmldoc.OuterXml;

                        ////Call eConnect to process the xmldocument.
                        //e.CreateEntity(_dynamicsConnection, xmldocument);

                        //////////////////////////////////////////////////////////////////////////////////

                        operationResult.Success = true;
                        operationResult.Message = "Success";
                    }
                    else
                    {
                        operationResult.Success = false;
                        operationResult.Message = "No items are attached to receive.";
                    }
                }
                // The eConnectException class will catch eConnect business logic errors.
                // display the error message on the console
                catch (eConnectException exc)
                {
                    operationResult.Success = false;
                    operationResult.Message = "Error";
                    logger.ErrorFormat("Error saving new receipt: {0} ", exc.ToString());
                }
                // Catch any system error that might occurr.
                // display the error message on the console
                catch (System.Exception ex)
                {
                    operationResult.Success = false;
                    operationResult.Message = "Error";
                    logger.ErrorFormat("Error saving new receipt: {0} ", ex.ToString());
                }
                finally
                {
                    // Call the Dispose method to release the resources
                    // of the eConnectMethds object
                    e.Dispose();
                }
            } // end of using statement

            return(operationResult);
        }
Exemple #44
0
        /// <summary>
        /// save new receivable transaction
        /// </summary>
        /// <param name="receivable"></param>
        /// <returns></returns>
        public OperationResult SaveReceivableTransaction(RM20101 receivable)
        {
            var operationResult = new OperationResult();

            logger.Debug("Receivable is being created...");

            using (eConnectMethods e = new eConnectMethods())
            {
                try
                {
                    // Instantiate a taPMTransactionInsert XML node object
                    taRMTransaction transaction = new taRMTransaction();

                    //Populate elements of the taUpdateCreateItemRcd XML node object
                    transaction.RMDTYPAL = receivable.RMDTYPAL;
                    transaction.DOCNUMBR = receivable.DOCNUMBR;
                    transaction.DOCDATE  = receivable.DOCDATE.ToShortDateString();
                    transaction.BACHNUMB = receivable.BACHNUMB;
                    transaction.CUSTNMBR = receivable.CUSTNMBR;
                    transaction.DOCAMNT  = receivable.DOCAMNT;
                    transaction.SLSAMNT  = receivable.SLSAMNT;

                    // Instantiate a PMTransactionType schema object
                    RMTransactionType transactiontype = new RMTransactionType();

                    // Populate the PMTransactionType schema with the taPMTransactionInsert XML node
                    transactiontype.taRMTransaction = transaction;
                    RMTransactionType[] receivableTransaction = { transactiontype };

                    // Instantiate an eConnectType schema object
                    eConnectType eConnect = new eConnectType();

                    // Instantiate a Memory Stream object
                    MemoryStream memoryStream = new MemoryStream();

                    // Create an XML serializer object
                    XmlSerializer serializer = new XmlSerializer(eConnect.GetType());

                    // Populate the eConnectType object with the PMTransactionType schema object
                    eConnect.RMTransactionType = receivableTransaction;

                    // Serialize the eConnectType.
                    serializer.Serialize(memoryStream, eConnect);

                    // Reset the position of the memory stream to the start.
                    memoryStream.Position = 0;

                    // Create an XmlDocument from the serialized eConnectType in memory.
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.Load(memoryStream);
                    memoryStream.Close();

                    // Call eConnect to process the XmlDocument.
                    e.CreateEntity(_dynamicsConnection, xmlDocument.OuterXml);

                    operationResult.Success = true;
                    operationResult.Message = "Success";
                }
                // The eConnectException class will catch eConnect business logic errors.
                // display the error message on the console
                catch (eConnectException exc)
                {
                    Console.Write(exc.ToString());
                    operationResult.Success = false;
                    operationResult.Message = "Error";
                    logger.ErrorFormat("Error saving new payables transaction: {0} ", exc.ToString());
                }
                // Catch any system error that might occurr.
                // display the error message on the console
                catch (System.Exception ex)
                {
                    Console.Write(ex.ToString());
                    operationResult.Success = false;
                    operationResult.Message = "Error";
                    logger.ErrorFormat("Error saving new payables transaction: {0} ", ex.ToString());
                }
                finally
                {
                    // Call the Dispose method to release the resources
                    // of the eConnectMethds object
                    e.Dispose();
                }
            } // end of using statement

            return(operationResult);
        }