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; }
public static bool UpdateEntity(ref string response, string transactionXML, string companyDB) { string connString = DataAccess.ConnectionStringWindows; bool returnValue; response = ""; eConnectMethods eConnCall = new eConnectMethods(); try { returnValue = eConnCall.UpdateEntity(connString, transactionXML); return(true); } catch (eConnectException ex) { response = ex.Message; return(false); } catch (SqlException ex) { foreach (SqlError sqlErr in ex.Errors) { response += sqlErr.Message + "\r\n"; } return(false); } catch (Exception ex) { response = ex.Message; return(false); } }
// public static string InvoiceDOCID(string con) // { // SqlCommand command = new SqlCommand(); // string res = ""; // command.Connection = new SqlConnection(con); // command.CommandType = System.Data.CommandType.Text; // command.CommandText = "SELECT INVDOCID FROM SOP40100"; // try{ // if(command.Connection.State != ConnectionState.Open) // { // command.Connection.Open(); // } // res = (string) command.ExecuteScalar(); // }catch(Exception ex) // { // IEvent e = new ErrorEvent("","",ex.Message); // e.Publish(); // }finally // { // command.Connection.Close(); // } // return res; //} //public static string returnDOCID(string con) //{ // SqlCommand command = new SqlCommand(); // string res = ""; // command.Connection = new SqlConnection(con); // command.CommandType = System.Data.CommandType.Text; // command.CommandText = "SELECT RETDOCID FROM SOP40100"; // try // { // if (command.Connection.State != ConnectionState.Open) // { // command.Connection.Open(); // } // res = (string)command.ExecuteScalar(); // } // catch (Exception ex) // { // IEvent e = new ErrorEvent("", "", ex.Message); // e.Publish(); // } // finally // { // command.Connection.Close(); // } // return res; //} //public static bool insertFiscalInfo(string SOPNUMBE, string COO, string DATEGEN, string SERIALPRINTER,string con) //{ // SqlCommand command = new SqlCommand(); // bool res = false; // command.Connection = new SqlConnection(con); // command.CommandType = System.Data.CommandType.Text; // command.Parameters.AddWithValue("@INVOICE", SOPNUMBE); // command.Parameters.AddWithValue("@COO", COO); // command.Parameters.AddWithValue("@DATEGEN", DATEGEN); // command.Parameters.AddWithValue("@SERIALPRINTER", SERIALPRINTER); // command.CommandText = "INSERT INTO CSG_FISCAL_PRINT (COO,INVOICE,DATEGEN,SERIALPRINTER) VALUES(@COO,@INVOICE,@DATEGEN,@SERIALPRINTER);"; // try // { // if (command.Connection.State != ConnectionState.Open) // { // command.Connection.Open(); // } // res = command.ExecuteNonQuery()>0; // } // catch (Exception ex) // { // IEvent e = new ErrorEvent("", "", ex.Message); // e.Publish(); // } // finally // { // command.Connection.Close(); // } // return res; //} public static bool eConnectSendToGP(string eConnectDocument, string TrustedConnStr) { //string status; bool res = true; // ((IEvent)(new InfoEvent("", "", "Documento a Procesar: " + eConnectDocument))).Publish(); try { eConnectMethods eConCall = new eConnectMethods(); //'Dim econnect As New eConnectType //' Dim serializer As New XmlSerializer(GetType(eConnectType)) //' Dim memstream As New MemoryStream //' Dim scServices = New ServiceController //'scServices = ServiceController.GetServices(); //' scService.ServiceName == "DynGP11eConnect" //'MsgBox(eConnect_ConnectionString) res = eConCall.eConnect_EntryPoint(TrustedConnStr, EnumTypes.ConnectionStringType.SqlClient, eConnectDocument, EnumTypes.SchemaValidationType.None, ""); //'status = eConCall.CreateTransactionEntity(eConnect_ConnectionString, Xml) }catch (Exception ex) { // res = false; // IEvent e = new ErrorEvent("","","Error en la transacción: " + ex.Message); //e.Publish(); } finally {} return(res); }
public static Boolean SendData(string xmlDocument) { eConnectMethods eConCall = new eConnectMethods(); try { //Create a connection string to the Microsoft Dynamics GP database server //string cnnString = ConfigurationManager.AppSettings["GPCnnString"]; //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"]; //Use the eConnect_EntryPoint to create the document in Microsoft Dynamics GP eConCall.eConnect_EntryPoint(FactoryCompany.ErpConnection.CnnString, EnumTypes.ConnectionStringType.SqlClient, xmlDocument, EnumTypes.SchemaValidationType.None, ""); return(true); } catch (eConnectException) { throw; //return false; } catch (Exception) { throw; //return false; } }
private void btnSend_Click(object sender, System.EventArgs e) { eConnectMethods eConnect = new eConnectMethods(); XmlDocument myXmlDoc = new XmlDocument(); XmlNode eConnectProcessInfoOutgoing; try { checkBox1.Checked = false; myXmlDoc.LoadXml(txtXml.Text); eConnectProcessInfoOutgoing = myXmlDoc.SelectSingleNode("//Outgoing"); if ((eConnectProcessInfoOutgoing == null) || (string.IsNullOrEmpty(eConnectProcessInfoOutgoing.InnerText) == true)) { eConnect.eConnect_EntryPoint(txtConnString.Text, EnumTypes.ConnectionStringType.SqlClient, myXmlDoc.OuterXml, EnumTypes.SchemaValidationType.None, string.Empty); this.txtResults.Text = "Message successfully entered into the BackOffice."; } else { if (eConnectProcessInfoOutgoing.InnerText == "TRUE") { this.txtResults.Text = eConnect.eConnect_Requester(txtConnString.Text, EnumTypes.ConnectionStringType.SqlClient, myXmlDoc.OuterXml); } } } catch (Exception ex) { this.txtResults.Text = ex.ToString(); } finally { eConnect.Dispose(); } }
/// <summary> /// Integra un documento xml sDocXml a GP. /// </summary> public void integraTransactionXml() { iError = 0; string eConnResult; eConnectMethods eConnObject = new eConnectMethods(); try { //El método que integra eConnect_EntryPoint retorna True si fue exitoso //eConnResult = eConnObject.eConnect_EntryPoint(_DatosConexionDB.Elemento.ConnStr, EnumTypes.ConnectionStringType.SqlClient, _sDocXml, EnumTypes.SchemaValidationType.None); eConnResult = eConnObject.CreateTransactionEntity(_DatosConexionDB.Elemento.ConnStr, _sDocXml); this.sMensaje = "--> Integrado a GP"; //sMensaje += _sDocXml; } catch (eConnectException eConnErr) { this.sMensaje = "Excepción eConnect: " + eConnErr.Message + " " + eConnErr.TargetSite.ToString() + " [integraTransactionXml] " + _sDocXml; this.iError++; } catch (ApplicationException ex) { this.sMensaje = "Excepción de aplicación: " + ex.Message + "[integraTransactionXml]"; this.iError++; } catch (Exception errorGral) { this.sMensaje = "Excepción desconocida: " + errorGral.Message + "[integraTransactionXml]"; this.iError++; } }
private void saveToSOP(Transaction assessment, string documentID, string defaultSiteID) { try { using (eConnectMethods eConnect = new eConnectMethods()) { string sAssessment; string sXSD; XmlDocument XSDdoc = new XmlDocument(); XSDdoc.Load(@"eConnect.xsd"); sXSD = XSDdoc.OuterXml; serializeSOPObject("assessment.xml", assessment, documentID, defaultSiteID); XmlDocument xmldoc = new XmlDocument(); xmldoc.Load("assessment.xml"); sAssessment = xmldoc.OuterXml; eConnect.eConnect_EntryPoint(connString, EnumTypes.ConnectionStringType.SqlClient, sAssessment, EnumTypes.SchemaValidationType.XSD, sXSD); rollback = false; //20100625 } } catch (Exception ex) { log.Error(ex); throw ex; } }
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()); } }
/// <summary> /// update part master /// </summary> /// <param name="part"></param> /// <returns></returns> public OperationResult UpdatePartMaster(IV00101_Part_Master part) { var operationResult = new OperationResult(); var existingPart = _dynamicsContext.IV00101_Part_Master.FirstOrDefault(x => x.ITEMNMBR.Replace(" ", string.Empty).ToLower() == part.ITEMNMBR.Replace(" ", string.Empty).ToLower()); if (existingPart != null) { logger.Debug("Part Master is being updated."); using (eConnectMethods e = new eConnectMethods()) { try { using (SqlConnection connection = new SqlConnection(_dynamicsConnection)) { connection.Open(); SqlCommand cmd = new SqlCommand("UPDATE dbo.IV00101 SET STNDCOST = @StandardCost, ITEMSHWT = @Weight WHERE ITEMNMBR = @ItemNumber"); cmd.CommandType = CommandType.Text; cmd.Connection = connection; cmd.Parameters.AddWithValue("@ItemNumber", part.ITEMNMBR); cmd.Parameters.AddWithValue("@StandardCost", part.STNDCOST); cmd.Parameters.AddWithValue("@Weight", part.ITEMSHWT); cmd.ExecuteNonQuery(); connection.Close(); } operationResult.Success = true; operationResult.Message = "Success"; } // 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 updating part currency: {0} ", ex.ToString()); } } // end of using statement } else { operationResult.Success = false; operationResult.Message = "Unable to find selected part currency."; } return(operationResult); }
public static void GP() { string econnectDocument; string sXsdSchema; string sConnectionString; //Generate the eConnectXml string xmlRendered = @"PM_Transaction-Invoice.xml"; using (eConnectMethods e = new eConnectMethods()) { try { XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(xmlRendered); econnectDocument = xmldoc.OuterXml; //User ID=sa;Password=sa sConnectionString = @"Data Source=LAPTOP-BUDQ9SBN\DYNAMICGP;Integrated Security = SSPI; Persist Security Info = false ; Initial Catalog = GP_DE;"; // 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. bool response = e.CreateEntity(sConnectionString, econnectDocument); Console.WriteLine(response); Console.ReadLine(); } // The eConnectException class will catch eConnect business logic errors. // display the error message on the console catch (eConnectException exc) { Console.Write(exc.ToString()); e.Dispose(); } // Catch any system error that might occurr. // display the error message on the console catch (System.Exception ex) { Console.Write(ex.ToString()); e.Dispose(); } } }
static void Main() { string sCustomerDocument; string sXsdSchema; string sConnectionString; using (eConnectMethods e = new eConnectMethods()) { try { // Create the customer data file SerializeCustomerObject("Customer.xml"); // Use an XML document to create a string representation of the customer XmlDocument xmldoc = new XmlDocument(); xmldoc.Load("Customer.xml"); sCustomerDocument = xmldoc.OuterXml; // Specify the Microsoft Dynamics GP server and database in the connection string sConnectionString = @"data source=MYSERVER;initial catalog=DATABASE;integrated security=SSPI;persist security info=False;packet size=4096"; // Create an XML Document object for the schema XmlDocument XsdDoc = new XmlDocument(); // Default path to the eConnect.xsd file // Change the filepath if the eConnect 10.0.0.0 SDK is installed in a location other than the default. XsdDoc.Load(@"\Program files\Common Files\Microsoft Shared\eConnect 10\XML Schemas\Incoming XSD Schemas\eConnect.xsd"); // Create a string representing the eConnect schema sXsdSchema = XsdDoc.OuterXml; // Pass in xsdSchema to validate against. e.eConnect_EntryPoint(sConnectionString, EnumTypes.ConnectionStringType.SqlClient, sCustomerDocument, EnumTypes.SchemaValidationType.XSD, sXsdSchema); } // The eConnectException class will catch eConnect business logic errors. // display the error message on the console catch (eConnectException exc) { Console.Write(exc.ToString()); } // Catch any system error that might occurr. // display the error message on the console catch (System.Exception ex) { Console.Write(ex.ToString()); } } // end of using statement }
/// <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); }
public void createNewItem(part newpart) { using (eConnectMethods eConCall = new eConnectMethods()) { try { // Create the eConnect document and store it in a file serializeObject("C:\\newItem.xml", newpart); // Load the eConnect XML document from the file into // and XML document object XmlDocument xmldoc = new XmlDocument(); xmldoc.Load("C:\\newItem.xml"); // Create an XML string from the document object string salesOrderDocument = xmldoc.OuterXml; // Create a connection string // Integrated Security is required. Integrated security=SSPI // Update the data source and initial catalog to use the names of // data server and company database string sConnectionString = "data source=Sandbox-PC\\DTIGP;initial catalog=DTI;integrated security=SSPI;persist security info=False;packet size=4096"; // Use the CreateTransactionEntity method to create the sales document in Microsoft Dynamics GP // The method returns a string that contains the doc ID number of the new sales document string salesOrder = eConCall.CreateTransactionEntity(sConnectionString, salesOrderDocument); } // The eConnectException class will catch any business logic related errors from eConnect_EntryPoint. catch (eConnectException exp) { Console.Write(exp.ToString()); } // Catch any system error that might occurr. Display the error to the user catch (Exception ex) { Console.Write(ex.ToString()); } finally { // Use the Dipose method to release resources associated with the // eConnectMethods objects eConCall.Dispose(); } } }
public Response CreateGPMaster(string strCNX, string strXML) { var eConnCall = new eConnectMethods(); var response = new Response(); try { response.SUCCESS = eConnCall.CreateEntity(strCNX, strXML); response.MESSAGE = "EXITO"; return(response); } catch (eConnectException ex) { response.SUCCESS = false; response.MESSAGE = ex.Message; response.STACK = ex.StackTrace; if (ex.InnerException != null) { response.STACK += ex.InnerException.Message; } return(response); } catch (Exception ex) { response.SUCCESS = false; response.MESSAGE = ex.Message; response.STACK = ex.StackTrace; if (ex.InnerException != null) { response.STACK += ex.InnerException.Message; } return(response); } finally { eConnCall.Dispose(); } }
public static void MySer() { using (eConnectMethods eConCall = new eConnectMethods()) { try { // Create the eConnect document and store it in a file SerializeObject("SalesOrder.xml"); // Load the eConnect XML document from the file into // and XML document object XmlDocument xmldoc = new XmlDocument(); xmldoc.Load("SalesOrder.xml"); string salesOrderDocument = xmldoc.OuterXml; string sConnectionString = @"Data Source=LAPTOP-BUDQ9SBN\DYNAMICGP;Integrated Security = SSPI; Persist Security Info = false ; Initial Catalog = GP_DE;"; string salesOrder = eConCall.CreateTransactionEntity(sConnectionString, salesOrderDocument); Console.WriteLine(salesOrder); Console.ReadLine(); } catch (eConnectException exp) { Console.Write(exp.ToString()); Console.ReadLine(); } catch (Exception ex) { Console.Write(ex.ToString()); Console.ReadLine(); } finally { eConCall.Dispose(); } } }
public void PushtoGP(XElement payablex) { eConnectMethods e = new eConnectMethods(); string payableVoucher = payablex.ToString(); // Specify the Microsoft Dynamics GP server and database in the connection string string sConnectionString = @"data source=sc-gpd;initial catalog=TMI;integrated security=SSPI;persist security info=False;packet size=4096"; // Create an XML Document object for the schema XmlDocument XsdDoc = new XmlDocument(); // Default path to the eConnect.xsd file // Change the filepath if the eConnect 10.0.0.0 SDK is installed in a location other than the default. XsdDoc.Load(@"C:\Program Files (x86)\Common Files\Microsoft Shared\eConnect 10\XML Sample Documents\Incoming XSD Schemas\eConnect.xsd"); // Create a string representing the eConnect schema string sXsdSchema = XsdDoc.OuterXml; // Pass in xsdSchema to validate against. e.eConnect_EntryPoint(sConnectionString, EnumTypes.ConnectionStringType.SqlClient, payableVoucher, EnumTypes.SchemaValidationType.XSD, sXsdSchema); }
/////// //// GPQueOverLoad to Just get One Employee public XElement GPQue(string employeeID) { string pasheet; var xpasheet = new XElement("eConnect", new XElement("RQeConnectOutType", new XElement("eConnectProcessInfo", new XElement("Outgoing", "TRUE"), new XElement("MessageID", "Employee")), new XElement("eConnectOut", new XElement("DOCTYPE", "Employee"), new XElement("INDEX1FROM", employeeID), new XElement("INDEX1TO", employeeID), new XElement("OUTPUTTYPE", "2"), new XElement("FORLOAD", "0"), new XElement("FORLIST", "1"), new XElement("ACTION", "0"), new XElement("ROWCOUNT", "1"), new XElement("REMOVE", "0")))); pasheet = xpasheet.ToString(); // 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=sc-gpd;initial catalog=TMI;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, pasheet); // Display the result of the eConnect_Requester method call //Console.Write(reqDoc); XElement blob = XElement.Parse(reqDoc); return(blob); }
/// <summary> /// Integra un documento xml sDocXml a GP. /// </summary> public void integraEntityXml() { iError = 0; bool eConnResult; eConnectMethods eConnObject = new eConnectMethods(); try { //El método que integra eConnect_EntryPoint retorna True si fue exitoso //eConnResult = eConnObject.eConnect_EntryPoint(_DatosConexionDB.Elemento.ConnStr, EnumTypes.ConnectionStringType.SqlClient, _sDocXml, EnumTypes.SchemaValidationType.None); eConnResult = eConnObject.CreateEntity(_DatosConexionDB.Elemento.ConnStr, _sDocXml); if (eConnResult) { sMensaje = "--> Integrado a GP"; } else { iError++; sMensaje = "Error desconocido al crear la entidad eConnect."; } } catch (eConnectException eConnErr) { sMensaje = "Excepción eConnect: " + eConnErr.Message + "[IntegraComprasGP.integraEntityXml]"; iError++; } catch (ApplicationException ex) { sMensaje = "Excepción de aplicación: " + ex.Message + "[IntegraComprasGP.integraEntityXml]"; iError++; } catch (Exception errorGral) { sMensaje = "Excepción desconocida: " + errorGral.Message + "[IntegraComprasGP.integraEntityXml]"; iError++; } }
private void CreateSalesInv_eConnect(DataTable tbl, int xPos) { this.eConnObject = new eConnectMethods(); this.xmlDoc = new XmlDocument(); DataTable sopLine = this.cData.GetSopLine(Convert.ToInt32(tbl.Rows[xPos]["idventa"])); sopLine.TableName = "taSopLineIvcInsert"; sopLine.DataSet.DataSetName = "taSopLineIvcInsert_Items"; string str1 = "<eConnect><SOPTransactionType>" + sopLine.DataSet.GetXml(); DataTable sopPayment = this.cData.GetSopPayment(Convert.ToInt32(tbl.Rows[xPos]["idventa"]), this.sChequeraId); sopPayment.TableName = "taCreateSopPaymentInsertRecord"; sopPayment.DataSet.DataSetName = "taCreateSopPaymentInsertRecord_Items"; string xml1 = sopPayment.DataSet.GetXml(); string str2 = str1 + xml1; DataTable sopUserDef = this.cData.GetSopUserDef(Convert.ToInt32(tbl.Rows[xPos]["idventa"])); sopUserDef.TableName = "taSopUserDefined"; sopUserDef.DataSet.DataSetName = "dataset"; string str3 = sopUserDef.DataSet.GetXml().Replace("<dataset>", "").Trim().Replace("</dataset>", "").Trim(); string str4 = str2 + str3; DataTable sopMultiBin = this.cData.GetSopMultiBin(Convert.ToInt32(tbl.Rows[xPos]["idventa"])); sopMultiBin.TableName = "taSopMultiBin"; sopMultiBin.DataSet.DataSetName = "taSopMultiBin_Items"; string xml2 = sopMultiBin.DataSet.GetXml(); string str5 = str4 + xml2; DataTable sopHdr = this.cData.GetSopHdr(Convert.ToInt32(tbl.Rows[xPos]["idventa"])); sopHdr.TableName = "taSopHdrIvcInsert"; sopHdr.DataSet.DataSetName = "dataset"; string str6 = sopHdr.DataSet.GetXml().Replace("<dataset>", "").Trim().Replace("</dataset>", "").Trim(); this.xmlDoc.LoadXml(str5 + str6 + "</SOPTransactionType></eConnect>"); this.eConnResult = this.eConnObject.eConnect_EntryPoint(this.sConn, EnumTypes.ConnectionStringType.SqlClient, this.xmlDoc.OuterXml, EnumTypes.SchemaValidationType.None, ""); }
// public static string InvoiceDOCID(string con) // { // SqlCommand command = new SqlCommand(); // string res = ""; // command.Connection = new SqlConnection(con); // command.CommandType = System.Data.CommandType.Text; // command.CommandText = "SELECT INVDOCID FROM SOP40100"; // try{ // if(command.Connection.State != ConnectionState.Open) // { // command.Connection.Open(); // } // res = (string) command.ExecuteScalar(); // }catch(Exception ex) // { // IEvent e = new ErrorEvent("","",ex.Message); // e.Publish(); // }finally // { // command.Connection.Close(); // } // return res; //} //public static string returnDOCID(string con) //{ // SqlCommand command = new SqlCommand(); // string res = ""; // command.Connection = new SqlConnection(con); // command.CommandType = System.Data.CommandType.Text; // command.CommandText = "SELECT RETDOCID FROM SOP40100"; // try // { // if (command.Connection.State != ConnectionState.Open) // { // command.Connection.Open(); // } // res = (string)command.ExecuteScalar(); // } // catch (Exception ex) // { // IEvent e = new ErrorEvent("", "", ex.Message); // e.Publish(); // } // finally // { // command.Connection.Close(); // } // return res; //} //public static bool insertFiscalInfo(string SOPNUMBE, string COO, string DATEGEN, string SERIALPRINTER,string con) //{ // SqlCommand command = new SqlCommand(); // bool res = false; // command.Connection = new SqlConnection(con); // command.CommandType = System.Data.CommandType.Text; // command.Parameters.AddWithValue("@INVOICE", SOPNUMBE); // command.Parameters.AddWithValue("@COO", COO); // command.Parameters.AddWithValue("@DATEGEN", DATEGEN); // command.Parameters.AddWithValue("@SERIALPRINTER", SERIALPRINTER); // command.CommandText = "INSERT INTO CSG_FISCAL_PRINT (COO,INVOICE,DATEGEN,SERIALPRINTER) VALUES(@COO,@INVOICE,@DATEGEN,@SERIALPRINTER);"; // try // { // if (command.Connection.State != ConnectionState.Open) // { // command.Connection.Open(); // } // res = command.ExecuteNonQuery()>0; // } // catch (Exception ex) // { // IEvent e = new ErrorEvent("", "", ex.Message); // e.Publish(); // } // finally // { // command.Connection.Close(); // } // return res; //} public static bool eConnectSendToGP(string eConnectDocument, string TrustedConnStr) { //string status; bool res = true; try { eConnectMethods eConCall = new eConnectMethods(); res = eConCall.eConnect_EntryPoint(TrustedConnStr, EnumTypes.ConnectionStringType.SqlClient, eConnectDocument, EnumTypes.SchemaValidationType.None, ""); //'status = eConCall.CreateTransactionEntity(eConnect_ConnectionString, Xml) } catch (Exception ex) { string sSource; string sLog; string sEvent; sSource = "GP Integration TShirt"; sLog = "Application"; sEvent = ex.Message; if (!EventLog.SourceExists(sSource)) { EventLog.CreateEventSource(sSource, sLog); } EventLog.WriteEntry(sSource, sEvent); EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234); } finally { } return(res); }
private void button1_Click(object sender, EventArgs e) { internalCode = textBox1.Text; externallCode = textBox2.Text; // MessageBox.Show(socialSecurityRequest.ToString()); try { string pasheet; var xpasheet = new XElement("eConnect", new XElement("RQeConnectOutType", new XElement("eConnectProcessInfo", new XElement("Outgoing", "TRUE"), new XElement("MessageID", "Employee")), new XElement("eConnectOut", new XElement("DOCTYPE", "Employee"), new XElement("OUTPUTTYPE", "2"), new XElement("FORLOAD", "0"), new XElement("FORLIST", "1"), new XElement("ACTION", "0"), new XElement("ROWCOUNT", "4000"), new XElement("REMOVE", "0")))); pasheet = xpasheet.ToString(); // 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=VM-GPD01;initial catalog=TMI;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, pasheet); // Display the result of the eConnect_Requester method call //Console.Write(reqDoc); XElement blob = XElement.Parse(reqDoc); //Make Dictionary List of All Departments; var deptDictionary = new Dictionary<string, string>() { {"ACCT","25-" + internalCode +"-10-110-01"}, {"ADMIN","25-" + internalCode +"-10-140-01"}, {"AMBO","25-" + internalCode +"-40-210-06"}, {"AMID","25-" + internalCode +"-30-210-01"}, {"AMSC","25-" + internalCode +"-20-210-01"}, {"ARCMGT","25-" + externallCode +"-80-900-01"}, {"CNTADM","25-" + internalCode +"-10-135-01"}, {"CNTAVD","25-" + externallCode +"-20-800-01"}, {"CNTRBO","25-" + externallCode +"-40-500-06"}, {"CNTRCO","25-" + externallCode +"-20-500-08"}, {"CNTRCT","25-" + externallCode +"-20-500-01"}, {"CNTRID","25-" + externallCode +"-20-500-06"}, {"CNTRMN","25-" + externallCode +"-20-500-07"}, {"CNTRNC","25-" + externallCode +"-40-500-03"}, {"CNTRSF","25-" + externallCode +"-20-500-05"}, {"CNTRTX","25-" + externallCode +"-20-500-03"}, {"DMBO","25-" + internalCode +"-20-215-06"}, {"EXEC","25-" + internalCode +"-10-100-01"}, {"EXECEN","25-" + internalCode +"-10-100-04"}, {"FNANCE","25-" + internalCode +"-10-130-01"}, {"HR","25-" + internalCode +"-10-120-01"}, {"HR ID","25-" + internalCode +"-12-120-06"}, {"INFRBO","25-" + externallCode +"-30-700-06"}, {"INPRBO","25-" + internalCode +"-30-290-06"}, {"INSRBO","25-" + externallCode +"-30-300-06"}, {"INSRSC","25-" + externallCode +"-30-300-01"}, {"MGDEXC","25-" + internalCode +"-30-280-01"}, {"MIS","25-" + internalCode +"-10-160-01"}, {"MKTSAL","25-" + internalCode +"-20-205-01"}, {"MRKT","25-" + internalCode +"-10-170-01"}, {"OCIOSC","25-" + externallCode +"-60-800-01"}, {"OPEXEC","25-" + internalCode +"-10-139-01"}, {"PRJMGT","25-" + internalCode +"-20-229-01"}, {"RCRTBO","25-" + internalCode +"-10-220-06"}, {"RCRTEN","25-" + internalCode +"-10-220-04"}, {"RCRTM","25-" + internalCode +"-20-220-01"}, {"RCRTME","25-" + internalCode +"-10-228-01"}, {"RCRTU","25-" + internalCode +"-10-222-01"}, {"RCRUIT","25-" + internalCode +"-10-220-01"}, {"RMBO","25-" + internalCode +"-10-222-06"}, {"SALEBO","25-" + internalCode +"-40-200-06"}, {"SALEMG","25-" + internalCode +"-20-209-01"}, {"SALES","25-" + internalCode +"-20-200-01"}, {"SMSC","25-" + internalCode +"-20-235-01"}, {"TRANBO","25-" + externallCode +"-30-310-06"}, {"TSG","25-" + internalCode +"-20-230-01"}, {"SALEEN","25-" + internalCode +"-20-234-01"}, {"TSGMGS","25-" + externallCode +"-60-600-01"}, {"CNTRNY","25-" + externallCode +"-20-500-02"}, {"","MISSING"} }; //cool stuff down here int queryCount = blob.Elements("eConnect").Elements("Employee").Count(); string[,] employeeList = new string[queryCount, 10]; int rowCount = 0; int columnCount = 0; //Console.WriteLine(blob.ToString()); foreach (XElement employee in blob.Elements("eConnect").Elements("Employee")) { if (employee.Element("INACTIVE").Value == "0") { string mName; if (employeeIDRequest == true) { employeeList[rowCount, columnCount] = employee.Element("FRSTNAME").Value + " " + employee.Element("LASTNAME").Value; columnCount += 1; } if (employeeIDRequest == true) { employeeList[rowCount, columnCount] = employee.Element("FRSTNAME").Value + " " + employee.Element("LASTNAME").Value; columnCount += 1; } if (lastFirstMIRequest == true) { if (employee.Element("MIDLNAME").Value == "") { mName = ""; } else { mName = employee.Element("MIDLNAME").Value.Substring(0, 1) + "."; } employeeList[rowCount, columnCount] = employee.Element("LASTNAME").Value + ", " + employee.Element("FRSTNAME").Value + " " + mName; columnCount += 1; } employeeList[rowCount, columnCount] = employee.Element("DEPRTMNT").Value; columnCount += 1; if (socialSecurityRequest == true) { Func<string, string> socialize = s => { if (employee.Element("SOCSCNUM").Value == null) { s = ""; return s; } else { s = employee.Element("SOCSCNUM").Value; s = s[0] + s[1] + s[2] + "-" + s[3] + s[4] + "-" + s[5] + s[6] + s[7] + s[8]; return s; } }; employeeList[rowCount, columnCount] = socialize(employee.Element("SOCSCNUM").Value); columnCount += 1; } try { employeeList[rowCount, columnCount] = deptDictionary[employee.Element("DEPRTMNT").Value]; columnCount += 1; } catch { employeeList[rowCount, columnCount] = "MISSING"; columnCount += 1; } rowCount += 1; columnCount = 0; } } //doing excel stuff here Microsoft.Office.Interop.Excel.Application oXL; Microsoft.Office.Interop.Excel._Workbook oWB; Microsoft.Office.Interop.Excel._Worksheet oSheet; Microsoft.Office.Interop.Excel.Range oRng; oXL = new Microsoft.Office.Interop.Excel.Application(); oXL.Visible = true; oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(Missing.Value)); oSheet = (Excel._Worksheet)oWB.ActiveSheet; oSheet.Cells[1, 1] = "EMPLOYEE ID"; oSheet.Cells[1, 2] = "THI FORMAT NAME"; oSheet.Cells[1, 3] = "Department"; oSheet.Cells[1, 4] = "Code"; string endCornerSheet = "G" + (queryCount + 1).ToString(); Excel.Range employeeRange = oSheet.Range["A2", endCornerSheet]; employeeRange.Value2 = employeeList; //oRng = oSheet.get_Range("A2", endCornerSheet).Value2 = employeeRange; oRng = oSheet.get_Range("A2", endCornerSheet).Value2 = employeeList; } catch (Exception ex) {// Dislay any errors that occur to the console // MessageBox.Show(ex.ToString()); } }
public void Execute(string xml) { eConnectMethods eConnectObject = new eConnectMethods(); eConnectObject.eConnect_EntryPoint(connectionString, EnumTypes.ConnectionStringType.SqlClient, xml, EnumTypes.SchemaValidationType.None); }
/// <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); }
/// <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); }
/// <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> /// save new site /// </summary> /// <returns></returns> public OperationResult SaveSite() { var operationResult = new OperationResult(); logger.Debug("Site is being created..."); string sCustomerDocument; string sXsdSchema; string sConnectionString; using (eConnectMethods e = new eConnectMethods()) { try { // Create the site data file SerializeSiteObject("Site.xml"); // Use an XML document to create a string representation of the site XmlDocument xmldoc = new XmlDocument(); xmldoc.Load("Site.xml"); sCustomerDocument = xmldoc.OuterXml; // Specify the Microsoft Dynamics GP server and database in the connection string sConnectionString = @"data source=SLM-DYNAMICS;Database=STHLD;User Id=programmer;Password=programmer;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); operationResult.Success = true; operationResult.Message = "Successfully added a site."; } // 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 site: {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 site: {0} ", ex.ToString()); } finally { // Call the Dispose method to release the resources // of the eConnectMethds object e.Dispose(); } } // end of using statement //try //{ // var newSite = new IV40700_Site() // { // LOCNCODE = site.LOCNCODE, // LOCNDSCR = site.LOCNDSCR, // NOTEINDX = site.NOTEINDX, // ADDRESS1 = site.ADDRESS1, // ADDRESS2 = site.ADDRESS2, // ADDRESS3 = site.ADDRESS3, // CITY = site.CITY, // STATE = site.STATE, // ZIPCODE = site.ZIPCODE, // COUNTRY = site.COUNTRY, // PHONE1 = site.PHONE1, // PHONE2 = site.PHONE2, // PHONE3 = site.PHONE3, // FAXNUMBR = site.FAXNUMBR, // Location_Segment = site.Location_Segment, // STAXSCHD = site.STAXSCHD, // PCTAXSCH = site.PCTAXSCH, // INCLDDINPLNNNG = site.INCLDDINPLNNNG, // PORECEIPTBIN = site.PORECEIPTBIN, // PORETRNBIN = site.PORETRNBIN, // SOFULFILLMENTBIN = site.SOFULFILLMENTBIN, // SORETURNBIN = site.SORETURNBIN, // BOMRCPTBIN = site.BOMRCPTBIN, // MATERIALISSUEBIN = site.MATERIALISSUEBIN, // WMSINT = site.WMSINT, // PICKTICKETSITEOPT = site.PICKTICKETSITEOPT, // BINBREAK = site.BINBREAK, // CCode = site.CCode, // DECLID = site.DECLID, // INACTIVE = site.INACTIVE, // DEX_ROW_ID = site.DEX_ROW_ID // }; // _dynamicsContext.IV40700_Site.InsertOnSubmit(newSite); // _dynamicsContext.SubmitChanges(); // operationResult.Success = true; // operationResult.Message = "Success"; //} //catch (Exception ex) //{ // operationResult.Success = false; // operationResult.Message = "Error"; // logger.ErrorFormat("Error saving new site: {0} ", ex.ToString()); //} return(operationResult); }
public int InsertXml(string xmlString) { string sConnectionString = ""; Log errorLog = new Log(@"C:\Sinex\errorLog.txt"); int errorCount = 0; errorLog.Clear(); try { StringBuilder sb = new StringBuilder(); sb = new StringBuilder(); sb.Append("<eConnect xmlns:dt=\"urn: schemas - microsoft - com:datatypes\">"); // sb.Append("<RMCustomerMasterType>"); sb.Append("<eConnectProcessInfo>"); sb.Append("</eConnectProcessInfo>"); sb.Append("<taPMTransactionInsert>"); sb.Append("<BACHNUMB>1</BACHNUMB>"); sb.Append("<VCHNUMWK>99999</VCHNUMWK>"); sb.Append("<VENDORID>ACETRAVE0001</VENDORID>"); sb.Append("<DOCNUMBR>99999</DOCNUMBR>"); sb.Append("<DOCTYPE>1</DOCTYPE>"); sb.Append("<DOCAMNT>99.99</DOCAMNT>"); sb.Append("<DOCDATE>2020-01-01</DOCDATE>"); sb.Append("<MSCCHAMT>0.00</MSCCHAMT>"); sb.Append("<PRCHAMNT>99.99</PRCHAMNT>"); sb.Append("<TAXAMNT>0.00</TAXAMNT>"); sb.Append("<FRTAMNT>0.00</FRTAMNT>"); sb.Append("<TRDISAMT>0.00</TRDISAMT>"); sb.Append("<CHRGAMNT>99.99</CHRGAMNT>"); sb.Append("<CASHAMNT>0.00</CASHAMNT>"); sb.Append("<CHEKAMNT>0.00</CHEKAMNT>"); sb.Append("<CRCRDAMT>0.00</CRCRDAMT>"); sb.Append("<DISTKNAM>0.00</DISTKNAM>"); sb.Append("</taPMTransactionInsert>"); //sb.Append("</RMCustomerMasterType>"); sb.Append("</eConnect>"); sConnectionString = "server=LAPTOP-G581GE4V\\SQL2016_GP2018R2;database=TWO;Integrated Security=SSPI;persist security info=False"; eConnectMethods eConnectObject = new eConnectMethods(); XmlDocument xmlDoc = new XmlDocument(); XmlDocument xmlDoc2 = new XmlDocument(); xmlString.Replace(" ", ""); xmlDoc.LoadXml(xmlString); bool eConnectResult; eConnectResult = eConnectObject.CreateEntity(sConnectionString, xmlDoc.OuterXml); return(errorCount); } catch (Exception ex) {// If an error occurs, diplay the error information to the user errorCount = errorCount + 1; int errorLocation = ex.Message.IndexOf("Error Number ="); int errorNumberLocation = errorLocation + 14; string errorNumber = ex.Message.Substring(errorNumberLocation, 6).Trim(); switch (errorNumber) { case "305": errorLog.Write($"ERROR: Document Number {docnumbr} already exists"); break; case "306": errorLog.Write($"ERROR: Voucher Number {vchnumwk} already exists"); break; default: errorLog.Error("Pmtransaction.InsertXml", ex); break; } } return(errorCount); }
//public void watcher_Created() public void watcher_Created(object sender, FileSystemEventArgs e) { string sSource; string sLog; string sEvent; string documentType; string sName = "RCT2001"; string pathFile = e.FullPath; try { Thread.Sleep(70000); //Then we need to check file is exist or not which is created. if (CheckFileExistance(wathO, e.Name)) { bool res = true; try { XDocument xml = XDocument.Load(pathFile); //lee xml para obtener datos y llenar lineas de tablas SElSI string value = File.ReadAllText(pathFile); //lee contenido XML para enviar a GP eConnectMethods eConCall = new eConnectMethods(); documentType = e.Name.Substring(0, 3); if (documentType == "AJP" || documentType == "RCT" || documentType == "TXI" || documentType == "CMB" || documentType == "MST") { res = eConCall.eConnect_EntryPoint(pathBD, EnumTypes.ConnectionStringType.SqlClient, value, EnumTypes.SchemaValidationType.None, ""); if (res) { System.IO.File.Move(pathFile, wathD + e.Name); //Update codigo int number = 0; int totalQty = 0; string qry = string.Empty; bool _result = false; int numberDocument = 0; string DocumentCode = string.Empty; switch (documentType) { case "AJP": var q = (from b in xml.Descendants("taIVTransactionHeaderInsert") select new { code = (string)b.Element("IVDOCNBR") ?? string.Empty }) .FirstOrDefault(); if (q != null) { DocumentCode = q.code; } numberDocument = GetNumber(DocumentCode); number = numberDocument + 1; //obtine numero de la secuencia y lo incremente en 1 qry = "UPDATE selSI_IV40100 SET selSI_NextNumber ='" + "00000" + number.ToString() + "' WHERE selSI_IV_Type_ID ='AJP'"; _result = InsertLineInTSGLV(qry); //actualiza secuencia de numero //qry = string.Empty; //qry += // "INSERT INTO SElSI_IV_TRX_DATE (ivdoctyp,docnumbr,docdate,inuser) VALUES "; //qry += "('1', 'AJP" + "00000" + numberDocument + "','" + DateTime.Now + // "','dbo')"; //_result = InsertLineInTSGLV(qry); //guarda Header //var _line = (from b in xml.Descendants("taIVTransactionLotInsert") // select new // { // totalUnits = (string) b.Element("SERLTQTY") ?? string.Empty, // }).ToList(); //totalQty += _line.Sum(item => Convert.ToInt32(item.totalUnits)); // //suma totalUnits //qry = ""; //qry += "INSERT INTO selSI_IV_TRX_HDR (IVDOCTYP,DOCNUMBR,TotalUnits) VALUES "; //qry += "('1', 'AJP" + "00000" + numberDocument + "','" + totalQty + "')"; //_result = InsertLineInTSGLV(qry); //guarda Linea break; case "RCT": var y = (from b in xml.Descendants("taPopRcptHdrInsert") select new { code = (string)b.Element("POPRCTNM") ?? string.Empty }) .FirstOrDefault(); if (y != null) { DocumentCode = y.code; } numberDocument = GetNumber(DocumentCode); number = numberDocument + 1; qry = "UPDATE pop40100 SET POPRCTNM ='" + "RCT" + number.ToString() + "' WHERE INDEX1 = 1"; _result = InsertLineInTSGLV(qry); //actualiza secuencia de numero break; case "TXI": var z = (from b in xml.Descendants("taIVTransferHeaderInsert") select new { code = (string)b.Element("IVDOCNBR") ?? string.Empty }) .FirstOrDefault(); if (z != null) { DocumentCode = z.code; } numberDocument = GetNumber(DocumentCode); number = numberDocument + 1; //obtine numero de la secuencia y lo incremente en 1 qry = "UPDATE selSI_IV40100 SET selSI_NextNumber ='" + "000" + number.ToString() + "' WHERE selSI_IV_Type_ID ='TXI'"; _result = InsertLineInTSGLV(qry); //actualiza secuencia de numero break; case "MST": var x = (from b in xml.Descendants("taIVTransactionHeaderInsert") select new { code = (string)b.Element("IVDOCNBR") ?? string.Empty }) .FirstOrDefault(); if (x != null) { DocumentCode = x.code; } numberDocument = GetNumber(DocumentCode); number = numberDocument + 1; //obtine numero de la secuencia y lo incremente en 1 qry = "UPDATE selSI_IV40100 SET selSI_NextNumber ='" + "000" + number.ToString() + "' WHERE selSI_IV_Type_ID ='MST'"; _result = InsertLineInTSGLV(qry); //actualiza secuencia de numero break; case "CMB": var w = (from b in xml.Descendants("taIVTransactionHeaderInsert") select new { code = (string)b.Element("IVDOCNBR") ?? string.Empty }) .FirstOrDefault(); if (w != null) { DocumentCode = w.code; } numberDocument = GetNumber(DocumentCode); number = numberDocument + 1; //obtine numero de la secuencia y lo incremente en 1 qry = "UPDATE selSI_IV40100 SET selSI_NextNumber ='" + "00000" + number.ToString() + "' WHERE selSI_IV_Type_ID ='CMB'"; _result = InsertLineInTSGLV(qry); //actualiza secuencia de numero break; } } else { System.IO.File.Move(pathFile, wathE + e.Name); } } else { sSource = "GP Services TShirt"; sLog = "Application"; sEvent = "Archivo no Reconocido, las tres primera iniciales del nombre del archivo deben coincidir con el tipo de documento"; if (!EventLog.SourceExists(sSource)) { EventLog.CreateEventSource(sSource, sLog); } EventLog.WriteEntry(sSource, sEvent); } } catch (Exception ex) { sSource = "GP Services TShirt"; sLog = "Application"; sEvent = ex.Message; if (!EventLog.SourceExists(sSource)) { EventLog.CreateEventSource(sSource, sLog); } EventLog.WriteEntry(sSource, sEvent); throw; } } } catch (Exception ex) { throw ex; } }
/// <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); } }
public static Boolean SendData(string xmlDocument) { eConnectMethods eConCall = new eConnectMethods(); try { //Create a connection string to the Microsoft Dynamics GP database server //string cnnString = ConfigurationManager.AppSettings["GPCnnString"]; //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"]; //Use the eConnect_EntryPoint to create the document in Microsoft Dynamics GP eConCall.eConnect_EntryPoint(FactoryCompany.ErpConnection.CnnString, EnumTypes.ConnectionStringType.SqlClient, xmlDocument, EnumTypes.SchemaValidationType.None, ""); return true; } catch (eConnectException) { throw; //return false; } catch (Exception) { throw; //return false; } }
/// <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); }
public bool createOrUpdateCustomer(Customer c) { bool status = false; if ((c.CustomerName == null) || (c.CustomerID == null) || (c.CustomerClass == null)) return false; eConnectMethods eConnect = new eConnectMethods(); try { StringBuilder xml = new StringBuilder(); xml.Append("<eConnect>"); xml.Append("<RMCustomerMasterType>"); xml.Append("<taUpdateCreateCustomerRcd>"); xml.Append("<CUSTNMBR><![CDATA[" + c.CustomerID + "]]></CUSTNMBR>"); xml.Append("<CUSTNAME><![CDATA[" + c.CustomerName + "]]></CUSTNAME>"); xml.Append("<CUSTCLAS><![CDATA[" + c.CustomerClass + "]]></CUSTCLAS>"); xml.Append("<INACTIVE><![CDATA[" + c.Inactive.GetHashCode() + "]]></INACTIVE>"); if (c.ShortName != null) xml.Append("<SHRTNAME><![CDATA[" + c.ShortName + "]]></SHRTNAME>"); if (c.StatementName != null) xml.Append("<STMTNAME><![CDATA[" + c.StatementName + "]]></STMTNAME>"); if (c.ShipTo != null) xml.Append("<PRSTADCD><![CDATA[" + c.ShipTo + "]]></PRSTADCD>"); if (c.StatementTo != null) xml.Append("<STADDRCD><![CDATA[" + c.StatementTo + "]]></<STADDRCD>"); if (c.BillTo != null) xml.Append("<PRBTADCD><![CDATA[" + c.BillTo + "]]></PRBTADCD>"); if (c.Type != null) xml.Append("<USERDEF1><![CDATA[" + c.Type + "]]></USERDEF1>"); if (c.StudentStatus != null) xml.Append("<USERDEF2><![CDATA[" + c.StudentStatus + "]]></USERDEF2>"); /* * This data is part of the address */ if (c.CustomerAddress.AddressString != null) { if (c.CustomerAddress.AddressString.Length < 50) { xml.Append("<ADDRESS1><![CDATA[" + c.CustomerAddress.AddressString + "]]></ADDRESS1>"); } else { xml.Append("<ADDRESS1><![CDATA[" + c.CustomerAddress.AddressString.Substring(0, 50) + "]]></ADDRESS1>"); xml.Append("<ADDRESS2><![CDATA[" + c.CustomerAddress.AddressString.Substring(50, c.CustomerAddress.AddressString.Length - 50) + "]]></ADDRESS2>"); } } if (c.CustomerAddress.AddressCode != null) xml.Append("<ADRSCODE><![CDATA[" + c.CustomerAddress.AddressCode + "]]></ADRSCODE>"); if (c.CustomerAddress.AddressContact != null) xml.Append("<CNTCPRSN><![CDATA[" + c.CustomerAddress.AddressContact + "]]></CNTCPRSN>"); if (c.CustomerAddress.City != null) xml.Append("<CITY><![CDATA[" + c.CustomerAddress.City + "]]></CITY>"); if (c.CustomerAddress.State != null) xml.Append("<STATE><![CDATA[" + c.CustomerAddress.State + "]]></STATE>"); if (c.CustomerAddress.Country != null) xml.Append("<COUNTRY><![CDATA[" + c.CustomerAddress.Country + "]]></COUNTRY>"); if (c.CustomerAddress.Zipcode != null) xml.Append("<ZIPCODE><![CDATA[" + c.CustomerAddress.Zipcode + "]]></ZIPCODE>"); if (c.CustomerAddress.PhoneNumber1 != null) xml.Append("<PHNUMBR1><![CDATA[" + c.CustomerAddress.PhoneNumber1 + "]]></PHNUMBR1>"); if (c.CustomerAddress.PhoneNumber2 != null) xml.Append("<PHNUMBR2><![CDATA[" + c.CustomerAddress.PhoneNumber2 + "]]></PHNUMBR2>"); if (c.CustomerAddress.FaxNumber != null) xml.Append("<FAX><![CDATA[" + c.CustomerAddress.FaxNumber + "]]></FAX>"); //CAUSES ERRORS IF COUNTRYCODE DOESNT EXIST //if (c.CustomerAddress.CountryCode != null) xml.Append("<CCODE>" + c.CustomerAddress.CountryCode + "</CCODE>"); xml.Append("<UseCustomerClass>1</UseCustomerClass>"); xml.Append("<UpdateIfExists>1</UpdateIfExists>"); xml.Append("</taUpdateCreateCustomerRcd>"); xml.Append("</RMCustomerMasterType>"); xml.Append("</eConnect>"); status = eConnect.eConnect_EntryPoint(sConnectionString, EnumTypes.ConnectionStringType.SqlClient, xml.ToString(), EnumTypes.SchemaValidationType.None, ""); } catch (eConnectException ex) { Console.WriteLine(ex.ToString()); } return status; }
/// <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; } }
/// <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); }
public static string NextSopDocumentNumber(string salesDocID) { GetNextDocNumbers sopTransNumber = new GetNextDocNumbers(); string nextTransactionNumber = string.Empty; string sConnectionString = ""; try { StringBuilder sb = new StringBuilder(); sb.Append("<eConnect xmlns:dt=\"urn: schemas - microsoft - com:datatypes\">"); sb.Append("<RMCustomerMasterType>"); sb.Append("<eConnectProcessInfo>"); sb.Append("</eConnectProcessInfo>"); sb.Append("<taUpdateCreateCustomerRcd>"); sb.Append("<CUSTNMBR>JEFF0002</CUSTNMBR>"); sb.Append("<CUSTNAME>JL Lawn Care Service</CUSTNAME>"); sb.Append("<STMTNAME>JL Lawn Care Service </STMTNAME>"); sb.Append("<SHRTNAME>JL Lawn Care</SHRTNAME>"); sb.Append("<ADRSCODE>PRIMARY </ADRSCODE>"); sb.Append("<ADDRESS1>123 Main Street</ADDRESS1>"); sb.Append("<CITY>Valley City </CITY>"); sb.Append("<STATE>ND </STATE>"); sb.Append("<ZIPCODE>58072 </ZIPCODE>"); sb.Append("<COUNTRY>USA </COUNTRY>"); sb.Append("<PHNUMBR1>55532336790000 </PHNUMBR1>"); sb.Append("<PHNUMBR2>55551161817181 </PHNUMBR2>"); sb.Append("<FAX>55584881000000 </FAX>"); sb.Append("<UPSZONE>red </UPSZONE>"); sb.Append("<SHIPMTHD>PICKUP </SHIPMTHD>"); sb.Append("<TAXSCHID>ILLINOIS</TAXSCHID>"); sb.Append("<PRBTADCD>PRIMARY </PRBTADCD>"); sb.Append("<PRSTADCD>PRIMARY </PRSTADCD>"); sb.Append("<STADDRCD>PRIMARY </STADDRCD>"); sb.Append("<SLPRSNID>GREG E.</SLPRSNID>"); sb.Append("<SALSTERR>TERRITORY 6</SALSTERR>"); sb.Append("<COMMENT1>comment1</COMMENT1>"); sb.Append("<COMMENT2>comment2</COMMENT2>"); sb.Append("<PYMTRMID>Net 30 </PYMTRMID>"); sb.Append("<CHEKBKID>PAYROLL </CHEKBKID>"); sb.Append("<KPCALHST>0 </KPCALHST>"); //sb.Append("<RMCSHACTNUMST>000-1200-00 </RMCSHACTNUMST>"); sb.Append("<UseCustomerClass>0</UseCustomerClass>"); sb.Append("<UpdateIfExists>1</UpdateIfExists>"); sb.Append("</taUpdateCreateCustomerRcd>"); sb.Append("</RMCustomerMasterType>"); sb.Append("</eConnect>"); sb = new StringBuilder(); sb.Append("<eConnect xmlns:dt=\"urn: schemas - microsoft - com:datatypes\">"); sb.Append("<RMCustomerMasterType>"); sb.Append("<eConnectProcessInfo>"); sb.Append("</eConnectProcessInfo>"); sb.Append("<taPMTransactionInsert>"); sb.Append("<BACHNUMB>1</BACHNUMB>"); sb.Append("<VCHNUMWK>99999</VCHNUMWK>"); sb.Append("<VENDORID>ACETRAVE0001</VENDORID>"); sb.Append("<DOCNUMBR>99999</DOCNUMBR>"); sb.Append("<DOCTYPE>1</DOCTYPE>"); sb.Append("<DOCAMNT>99.99</DOCAMNT>"); sb.Append("<DOCDATE>2020-01-01</DOCDATE>"); sb.Append("<MSCCHAMT>0.00</MSCCHAMT>"); sb.Append("<PRCHAMNT>99.99</PRCHAMNT>"); sb.Append("<TAXAMNT>0.00</TAXAMNT>"); sb.Append("<FRTAMNT>0.00</FRTAMNT>"); sb.Append("<TRDISAMT>0.00</TRDISAMT>"); sb.Append("<CHRGAMNT>99.99</CHRGAMNT>"); sb.Append("<CASHAMNT>0.00</CASHAMNT>"); sb.Append("<CHEKAMNT>0.00</CHEKAMNT>"); sb.Append("<CRCRDAMT>0.00</CRCRDAMT>"); sb.Append("<DISTKNAM>0.00</DISTKNAM>"); sb.Append("</taPMTransactionInsert>"); sb.Append("</RMCustomerMasterType>"); sb.Append("</eConnect>"); sConnectionString = "server=LAPTOP-G581GE4V\\SQL2016_GP2018R2;database=TWO;Integrated Security=SSPI;persist security info=False"; eConnectMethods eConnectObject = new eConnectMethods(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(sb.ToString()); bool eConnectResult; eConnectResult = eConnectObject.CreateEntity(sConnectionString, xmlDoc.OuterXml); return(nextTransactionNumber); } catch (Exception ex) {// If an error occurs, diplay the error information to the user MessageBox.Show(ex.Message); throw ex; } finally { sopTransNumber.Dispose(); } }
/////// //// GPQueOverLoad to Just get One Employee public XElement GPQue(string employeeID) { string pasheet; var xpasheet = new XElement("eConnect", new XElement("RQeConnectOutType", new XElement("eConnectProcessInfo", new XElement("Outgoing", "TRUE"), new XElement("MessageID", "Employee")), new XElement("eConnectOut", new XElement("DOCTYPE", "Employee"), new XElement("INDEX1FROM", employeeID), new XElement("INDEX1TO", employeeID), new XElement("OUTPUTTYPE", "2"), new XElement("FORLOAD", "0"), new XElement("FORLIST", "1"), new XElement("ACTION", "0"), new XElement("ROWCOUNT", "1"), new XElement("REMOVE", "0")))); pasheet = xpasheet.ToString(); // 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=sc-gpd;initial catalog=TMI;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, pasheet); // Display the result of the eConnect_Requester method call //Console.Write(reqDoc); XElement blob = XElement.Parse(reqDoc); return blob; }