I have got a problem with undestanding powershell cmdlet.
Task is, to deserialize a xml file. I have got a folder with a lot of xml files, I would like to read in an filter certain information using the deserializiation method. My supervisor mentioned that I should use powershell cmdlet... but I haven't heard anything of it before. So what is the benefit? And how do I create such a cmdlet.
That is my code so far:
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
namespace EdocX
{
[Cmdlet(VerbsCommon.Get, "test", SupportsShouldProcess = true)]
public class program : Cmdlet
{
public static string dirPath = #"N:\EGS_SDRE\OB\19_Schnittstellen_eDocX_ITAS\06_Matching EdocX-Objektbrief\01_exemplarische_XMLs_fuer_den_Import\RWA-Anlage"
public static List<string> dirs = new List<string>(Directory.GetFiles(dirPath, "*.xml"));
public static (string[], string[], string[,], string[,], string[,]) deserializeobject(string filename)
{
// Liste Prüfgrundlagen
List<string> pg = new List<string>();
pg.Add("GaVO");
pg.Add("VkVO");
pg.Add("VStättVO");
pg.Add("SPrüfV");
pg.Add("BetrVO");
pg.Add("BbgSGPrüfV");
pg.Add("BremAnlPrüfV");
pg.Add("PVO");
pg.Add("TPrüfVO");
pg.Add("BauPrüfVO M-V");
pg.Add("DVO-NBauO");
pg.Add("PrüfVO NRW");
pg.Add("HTechAnlV RP");
pg.Add("TPrüfVO");
pg.Add("SächsTechPrüfVO");
pg.Add("TAnlVO");
pg.Add("PrüfVO");
pg.Add("ThürTechPrüfVO");
// Auftraggeber - Var
string[] Auftraggeber;
string Name_AG = "";
string Stadt_AG = "";
string PLZ_AG = "";
string Straße_AG = "";
string Hausnummer_AG = "";
string Region_AG = "";
string PARNR_AG = "";
// Aufstellungsort - Var
string[] Aufstellungsort;
string Name_AO = "";
string Stadt_AO = "";
string PLZ_AO = "";
string Straße_AO = "";
string Hausnummer_AO = "";
string Region_AO = "";
string Land_AO = "";
// Anlage - Var
string[,] Anlagen;
string Materialnummer = "";
string EQnummer = "";
string Anlagentyp = "RWA-Anlage";
string[] InterneBezeichnung;
string[] Hersteller;
// Vorgang rückgemeldet - Var
string[,] Vorgang_rückgemeldet;
string Typ_VR = "Prüfung";
string Dienstleister = "TÜV SÜD Industrie Service GmbH";
string Durchführungsdatum = "";
string Maengel = "";
string Bemerkungstexte = "";
string Pruefgrundlage_VR = "";
// Vorgang zukünftig - Var
string[,] Vorgang_zukünftig;
string Typ_VZ = "Prüfung";
string Fälligkeit = "";
string Pruefgrundlage_VZ = "";
//****************************************************************************************************
//********************************************SERIALIZATION*******************************************
// new instance of XMLSerializer --> specifiying type
var serializer = new XmlSerializer(typeof(Document));
// read the XML document
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var encoding = Encoding.GetEncoding("Windows-1252");
using (var sr = new StreamReader(filename, encoding, true))
using (var reader = XmlReader.Create(sr))
{
// restore the object's state using the deserialize method
var i = (Document)serializer.Deserialize(reader);
//---------------------------------------Auftraggeber-----------------------------------------------
int count_Z1ZRMPA = i.IDOC.Z1ZRMDB.Z1ZRMPA.Count;
for (int c = 0; c < count_Z1ZRMPA; c++)
{
if (i.IDOC.Z1ZRMDB.Z1ZRMPA[c].TITLE == "Auftraggeber")
{
Name_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].NAME1 + i.IDOC.Z1ZRMDB.Z1ZRMPA[c].NAME2;
Stadt_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].CITY1;
PLZ_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].POST_CODE1;
Straße_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].STREET;
Hausnummer_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].HOUSE_NUM1;
Region_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].REGION;
PARNR_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].PARNR;
}
//---------------------------------------Aufstellungsort----------------------------------------
if (i.IDOC.Z1ZRMDB.Z1ZRMPA[c].TITLE == "Aufstellungsort")
{
Name_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].NAME1 + i.IDOC.Z1ZRMDB.Z1ZRMPA[c].NAME2;
Stadt_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].CITY1;
PLZ_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].POST_CODE1;
Straße_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].STREET;
Hausnummer_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].HOUSE_NUM1;
Region_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].REGION;
Land_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].COUNTRY;
}
}
//---------------------------------------Anlage----------------------------------------------------
Materialnummer = i.IDOC.Z1ZRMDB.MABEZ;
EQnummer = i.IDOC.Z1ZRMDB.OBJNR;
int count_ANLAGEPRFTXT = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.ANLAGE.PRFTXT.Count;
int AnzahlAnlagen = count_ANLAGEPRFTXT - 1;
InterneBezeichnung = new string[AnzahlAnlagen];
Hersteller = new string[AnzahlAnlagen];
for (int c = 1; c < count_ANLAGEPRFTXT; c++)
{
InterneBezeichnung[c - 1] = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.ANLAGE.PRFTXT[c].ENTRBEREICH;
Hersteller[c - 1] = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.ANLAGE.PRFTXT[c].HERSTELLER;
}
//---------------------------------------Vorgang rückgemeldet-------------------------------------
Durchführungsdatum = i.IDOC.Z1ZRMDB.PRFBER.DATEN.Pruefungszeitraum;
int count_PRFTXT = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT.Count;
for (int c = 0; c < count_PRFTXT; c++)
{
if (i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].KATEGORIE == "Grundlage")
{
string Pruefgrundlage = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].Value;
int count_pg = pg.Count;
for (int cc = 0; cc < count_pg; cc++)
{
if (Pruefgrundlage.Contains(pg[cc]) == true)
{
Pruefgrundlage_VR = pg[cc];
}
}
}
if (i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].ROWTYPE == "Zwischenüberschrift" && i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].PATTERN == "#KATEGORIE[../#KATEGORIE='Mangel' and ../#GEWICHT[not(contains(.,'Beseitigt'))]]")
{
string Maengelabruf = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].Value;
if (Maengelabruf == "Mängel")
{
Maengel = "Mängel_ja";
}
else
{
Maengel = "Mängel_nein";
}
}
if (i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].ROWTYPE == "Mangel" && i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].PATTERN == "#KATEGORIE[../#KATEGORIE='Mangel' and ../#GEWICHT[not(contains(.,'Beseitigt'))]]")
{
string Bemerkungstext = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].Value;
Bemerkungstexte += " " + Bemerkungstext;
}
}
//---------------------------------------Vorgang zukünftig--------------------------------------
int count_Z1ZRMAU = i.IDOC.Z1ZRMDB.Z1ZRMAU.Count;
for (int c = 0; c < count_Z1ZRMAU; c++)
{
if (i.IDOC.Z1ZRMDB.Z1ZRMAU[c].MNAME == "Nächste Wiederkehrende Prüfung")
{
Fälligkeit = i.IDOC.Z1ZRMDB.Z1ZRMAU[c].MWERT;
}
}
for (int c = 0; c < count_PRFTXT; c++)
{
if (i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].KATEGORIE == "Grundlage")
{
string Pruefgrundlage = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].Value;
int count_pg = pg.Count;
for (int cc = 0; cc < count_pg; cc++)
{
if (Pruefgrundlage.Contains(pg[cc]) == true)
{
Pruefgrundlage_VZ = pg[cc];
}
}
}
}
Auftraggeber = new string[7];
Aufstellungsort = new string[7];
Anlagen = new string[AnzahlAnlagen, 5];
Vorgang_rückgemeldet = new string[AnzahlAnlagen, 6];
Vorgang_zukünftig = new string[AnzahlAnlagen, 3];
}
Auftraggeber[0] = Name_AG;
Auftraggeber[1] = Stadt_AG;
Auftraggeber[2] = PLZ_AG;
Auftraggeber[3] = Straße_AG;
Auftraggeber[4] = Hausnummer_AG;
Auftraggeber[5] = Region_AG;
Auftraggeber[6] = PARNR_AG;
Aufstellungsort[0] = Name_AO;
Aufstellungsort[1] = Stadt_AO;
Aufstellungsort[2] = PLZ_AO;
Aufstellungsort[3] = Straße_AO;
Aufstellungsort[4] = Hausnummer_AO;
Aufstellungsort[5] = Region_AO;
Aufstellungsort[6] = Land_AO;
for (int j = 0; j < Anlagen.GetLength(0); j++)
{
Anlagen[j, 0] = Materialnummer;
Anlagen[j, 1] = EQnummer;
Anlagen[j, 2] = Anlagentyp;
Anlagen[j, 3] = InterneBezeichnung[j];
Anlagen[j, 4] = Hersteller[j];
Vorgang_rückgemeldet[j, 0] = Typ_VR;
Vorgang_rückgemeldet[j, 1] = Dienstleister;
Vorgang_rückgemeldet[j, 2] = Durchführungsdatum;
Vorgang_rückgemeldet[j, 3] = Maengel;
Vorgang_rückgemeldet[j, 4] = Bemerkungstexte;
Vorgang_rückgemeldet[j, 5] = Pruefgrundlage_VR;
Vorgang_zukünftig[j, 0] = Typ_VZ;
Vorgang_zukünftig[j, 1] = Fälligkeit;
Vorgang_zukünftig[j, 2] = Pruefgrundlage_VZ;
}
return (Auftraggeber, Aufstellungsort, Anlagen, Vorgang_rückgemeldet, Vorgang_zukünftig);
}
}
}
And here the class to simulate the xml structure:
using System;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace EdocX
{//ZRM01 Root Environment
[Serializable()]
[XmlRoot(ElementName = "ZRM01")]
public partial class Document
{
[XmlElement()]
public ZRM01IDOC IDOC { get; set; }
}
//IDOC
[Serializable()]
public partial class ZRM01IDOC
{
[XmlElement()]
public ZRM01IDOCZ1ZRMDB Z1ZRMDB { get; set; }
}
//IDOC Elements
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDB
{
public string MABEZ { get; set; } // Materialnummer
public string OBJNR { get; set; } // Equipmentnummer
[XmlElement("Z1ZRMPA")]
public List<ZRM01IDOCZ1ZRMDBZ1ZRMPA> Z1ZRMPA = new List<ZRM01IDOCZ1ZRMDBZ1ZRMPA>(); //{ get; set; }
[XmlElement("Z1ZRMAU")]
public List<ZRM01IDOCZ1ZRMDBZ1ZRMAU> Z1ZRMAU = new List<ZRM01IDOCZ1ZRMDBZ1ZRMAU>();
[XmlElement()]
public ZRM01IDOCZ1ZRMDBPRFBER PRFBER { get; set; }
}
//Z1ZRMPA --> Mandant / Gebäude
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBZ1ZRMPA
{
[XmlAttribute()]
public string TITLE { get; set; } // "Auftraggeber" "Aufstellungsort"
[XmlElement()]
public string PARNR { get; set; } // Parnr. (Mandant)
[XmlElement()]
public string NAME1 { get; set; } // Name
[XmlElement()]
public string NAME2 { get; set; } // Name
[XmlElement()]
public string CITY1 { get; set; } // Stadt
[XmlElement()]
public string POST_CODE1 { get; set; } // PLZ
[XmlElement()]
public string STREET { get; set; } // Straße
[XmlElement()]
public string HOUSE_NUM1 { get; set; } // Hausnummer
[XmlElement()]
public string REGION { get; set; } // Region
[XmlElement()]
public string COUNTRY { get; set; } // Land
}
//Z1ZRMAU
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBZ1ZRMAU
{
[XmlElement()]
public string MNAME { get; set; } // "Nächste Wiederkehrende Prüfung"
[XmlElement()]
public string MWERT { get; set; } // Fälligkeit
}
//PRFBER Elemts
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBER
{
[XmlElement()]
public ZRM01IDOCZ1ZRMDBPRFBERPRFERG PRFERG { get; set; }
[XmlElement()]
public ZRM01IDOCZ1ZRMDBPRFBERDATEN DATEN { get; set; }
}
//DATEN
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERDATEN
{
[XmlElement()]
public string Pruefungszeitraum { get; set; } //Durchführungsdatum
}
//PRFERG Elements
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERPRFERG
{
[XmlElement()]
public ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGE ANLAGE { get; set; }
[XmlElement("PRFTXT")]
public List<ZRM01IDOCZ1ZRMDBPRFBERPRFERGPRFTXT> PRFTXT = new List<ZRM01IDOCZ1ZRMDBPRFBERPRFERGPRFTXT>();
}
//ANLAGE
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGE
{
[XmlElement("PRFTXT")]
public List<ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGEPRFTXT> PRFTXT = new List<ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGEPRFTXT>();
}
//PRFTXT
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGEPRFTXT
{
[XmlAttribute()]
public string REF { get; set; } // Anzahl Anlagen
[XmlAttribute()]
public string HERSTELLER { get; set; } // Hersteller Anlage
[XmlAttribute()]
public string ENTRBEREICH { get; set; } // Interne Bezeichnung Anlage
}
//PRFTXT
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERPRFERGPRFTXT
{
[XmlAttribute()]
public string KATEGORIE { get; set; } // A"Grundlage" < ... >
[XmlText()]
public string Value { get; set; }
[XmlAttribute()]
public string ROWTYPE { get; set; } // "Zwischenüberschrift" (für Mangel ja/nein) "Mangel" (für Bemerkungstext)
[XmlAttribute()]
public string PATTERN { get; set; } // "#KATEGORIE[../#KATEGORIE='Mangel' and ../#GEWICHT[not(contains(.,'Beseitigt'))]]" < Mängel > bzw < ... >
}
}
I'm very thankful for help!
Related
I trying to import data from excel and for each two connected column i store the data into two dimensional list except the last column which will be in a 1D list. i wanna assign an id for each set of data the code get to be able to build a dictionary later for them.
that means for the first( valLat and valLng together ) i want to assign id = 1 and so on for each List
for (int i = 2; i <= rowCount; i++)
{
var pickLocation = new PickLocation();
var valLat = ((Excel.Range)wks.Cells[i, PickLocation.ColumnLat]).Value;
var valLng = ((Excel.Range)wks.Cells[i, PickLocation.ColumnLng]).Value;
if (!(valLat == null) & !(valLng == null))
{
pickLocation.Lat = Convert.ToDouble(valLat);
pickLocation.Lng = Convert.ToDouble(valLng);
ListPickLocations.Add(pickLocation);
}
var setLocation = new SetLocation();
valLat = ((Excel.Range)wks.Cells[i, SetLocation.ColumnLat]).Value;
valLng = ((Excel.Range)wks.Cells[i, SetLocation.ColumnLng]).Value;
if (!(valLat == null) & !(valLng == null))
{
setLocation.Lat = Convert.ToDouble(valLat); ;
setLocation.Lng = Convert.ToDouble(valLng);
ListSetlocations.Add(setLocation);
}
var craneLocation = new CraneLocation();
valLat = ((Excel.Range)wks.Cells[i, CraneLocation.ColumnLat]).Value;
valLng = ((Excel.Range)wks.Cells[i, CraneLocation.ColumnLng]).Value;
if (!(valLat == null) & !(valLng == null))
{
craneLocation.Lat = Convert.ToDouble(valLat); ;
craneLocation.Lng = Convert.ToDouble(valLng);
ListCranelocations.Add(craneLocation);
}
var weight = ((Excel.Range)wks.Cells[i, 10]).Value;
if (!(weight == null))
{
Weights.Add(Convert.ToDouble(weight));
}
var clearance = ((Excel.Range)wks.Cells[2, 12]).Value;
if (!(clearance == null))
{
Clearance = clearance;
}
}
}
}
}
}
public class PickLocation
{
public double Lat { get; set; }
public double Lng { get; set; }
public static int ColumnLat { get; } = 4;
public static int ColumnLng { get; } = 5;
}
public class CraneLocation
{
public double Lat { get; set; }
public double Lng { get; set; }
public static int ColumnLat { get; } = 1;
public static int ColumnLng { get; } = 2;
}
public class SetLocation
{
public double Lat { get; set; }
public double Lng { get; set; }
public static int ColumnLat { get; } = 7;
public static int ColumnLng { get; } = 8;
}
Good day Stackoverflow,
I want to write some text at a specific point of a line in a txt-file.
So I want to write something between two ; in the line.
The Line of the textfile is: 20180912_0149;KIV\vischer;12.09.2018;01:49;; .
I want to write it if I click the "Geht" Button. I tried different things with streamreader and writer but I don't get to a solution.
Here is my code of the aspx.cs and my helper class:
Aspx.cs:
namespace Zieterfassung_0._0._2pre_alpha
{
public partial class Zeiten : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sPath = #"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung\obj\Debug\Zeiten.txt";
tb_User.Text = WindowsIdentity.GetCurrent().Name.ToString();
tb_Datum.Text = DateTime.Now.ToString("dd.MM.yyyy");
tb_Zeit.Text = DateTime.Now.ToString("hh:mm");
cZeile KommtDatumZeit = new cZeile();
if (File.Exists(sPath))
{
using (StreamReader sr = new StreamReader(sPath))
{
while (!sr.EndOfStream)
{
KommtDatumZeit = cZeiterfassung.GetZeileObjectFromZeileString(sr.ReadLine(), ";");
}
}
}
tb_Kommt.Text = KommtDatumZeit.dtKommt.ToString();
}
protected void btn_Geht_Click(object sender, EventArgs e)
{
string sAusgabeGeht = string.Format("{0:hh:mm}", tb_Zeit.Text);
string sPath = #"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung\obj\Debug\Zeiten.txt";
FileInfo fi = new FileInfo(sPath);
cZeile Geht = new cZeile();
using (StreamReader sr = new StreamReader(sPath))
{
Geht = cZeiterfassung.GetZeileObjectFromZeileString(sr.ReadLine(), ";");
}
using(StreamWriter sw = new StreamWriter(sPath))
{
}
}
}
}
Helperclass for splitting and array:
namespace Prog
{
public static class cZeiterfassung
{
public static cZeile GetZeileObjectFromZeileString(string Zeile, string Trenner)
{
cZeile ZeileReturn = new cZeile();
string[] separators = { Trenner };
string[] arZeile = Zeile.Split(separators, StringSplitOptions.None);
ZeileReturn.ID = arZeile[0];
if (arZeile[1].IndexOf("\\") != -1)
{
ZeileReturn.Domain = arZeile[1].Substring(0, arZeile[1].IndexOf("\\"));
if (arZeile[1].Length >= arZeile[1].IndexOf("\\"))
ZeileReturn.User = arZeile[1].Substring(arZeile[1].IndexOf("\\") + 1);
}
else
ZeileReturn.User = arZeile[1];
ZeileReturn.Datum = arZeile[2];
ZeileReturn.Kommt = arZeile[3];
ZeileReturn.Geht = arZeile[4];
if(!string.IsNullOrEmpty(arZeile[2]))
ZeileReturn.dtDatum = Convert.ToDateTime(arZeile[2]);
if(!string.IsNullOrEmpty(arZeile[3]))
ZeileReturn.dtKommt = Convert.ToDateTime(arZeile[3]);
if (!string.IsNullOrEmpty(arZeile[4]))
ZeileReturn.dtGeht = Convert.ToDateTime(arZeile[4]);
return ZeileReturn;
}
}//cZeiterfassung
public class cZeile
{
public string ID { get; set; }
public string Domain { get; set; }
public string User { get; set; }
public string Datum { get; set; }
public string Kommt { get; set; }
public string Geht { get; set; }
public DateTime dtDatum { get; set; }
public DateTime dtKommt { get; set; }
public DateTime dtGeht { get; set; }
public string Dauer { get; set; }
}
}
I can't quite Point out what are you trying to do from your code, but from the question you asked:
I would look into every line if you are looking for a specific line
string Data = "";
using(StreamReader Sr = new StreamReader(Path))
{
while(!Sr.EndOfStream())
{
string UseMe = Sr.ReadLine();
Data += UseMe;
}
}
Now you could just validate each line. With the Data-string I gave you a possibility to build each line into one string
I hope I could help you, otherwise contact me directly (I also speak german I guess this is easier for you)
If your file isn't big, I propose you to write to new files with new data.
This is the idea
string[] lines = File.ReadAllLines(sPath);
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].IndexOf(";;") != -1)
{
lines[i] = lines[i].Insert(line.IndexOf(";;"), "xxx");
}
}
File.WriteAllLines(sPathTemp, lines);
I'm using EDIFabric to build up an interchange and single message. I have a very simple format I need to output to an EDI x12 string. My code populates the interchange and group properly (viewing the local variables and collections), however when I run .ToEdi() on my interchange object I'm getting back empty message groups
My Output:
"ISA*00* *00* *IS*SenderID *IS*ReceiverID *160809*1008*^*00501*000001ISA*0*P*:~GS*FA*GS_02_SenderCode*GS_03_ReceiverCode*21160809*1008*00001GS06*X*005010~ST~AK1~AK2~IK3~IK5~AK9~SE~GE*000001*00001GS06~IEA*00001*000001ISA~"
Empty when shouldn't be
ST~AK1~AK2~IK3~IK5~AK9~SE~GE
Creation class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EdiFabric.Framework.Envelopes.X12;
using EdiFabric.Definitions.Hipaa_005010_999_X231;
using EdiFabric.Framework.Messages;
using EdiFabric.Framework.Envelopes;
namespace X12PayloadProcessing
{
public class DS_M_999
{
private DS_M_999_Interchange _Interchange;
private DS_M_999_Group _Group;
private Message _EDI_Message;
private S_ISA _EDI_ISA = new S_ISA();
private S_IEA _EDI_IEA = new S_IEA();
public Interchange _EDI_Interchange = new Interchange();
private S_GE _EDI_GE = new S_GE();
private S_GS _EDI_GS = new S_GS();
private Group _EDI_Group = new Group();
private M_999 _EDI_999 = new M_999();
private S_ST _EDI_ST = new S_ST();
private S_SE _EDI_SE = new S_SE();
private S_AK1 _EDI_AK1 = new S_AK1();
private S_AK2 _EDI_AK2 = new S_AK2();
private S_AK9 _EDI_AK9 = new S_AK9();
private S_IK3 _EDI_IK3 = new S_IK3();
private S_IK5 _EDI_IK5 = new S_IK5();
private List<G_TS999_2000> _EDI_2000_List = new List<G_TS999_2000>();
private G_TS999_2000 _EDI_2000 = new G_TS999_2000();
private G_TS999_2100 _EDI_2100 = new G_TS999_2100();
private List<G_TS999_2100> _EDI_2100_List = new List<G_TS999_2100>();
public DS_M_999(DS_M_999_Group Group, DS_M_999_Interchange Interchange)
{
_Group = Group;
_Interchange = Interchange;
_EDI_Interchange.Groups = new List<Group>();
_EDI_ISA.D_744_1 = _Interchange.ISA_01_Authorization.PadRight(2).Substring(0,2);
_EDI_ISA.D_745_2 = _Interchange.ISA_02_AuthInfo.PadRight(10).Substring(0,10);
_EDI_ISA.D_746_3 = _Interchange.ISA_03_SecurityQualifier.PadRight(2).Substring(0, 2);
_EDI_ISA.D_747_4 = _Interchange.ISA_04_Password.PadRight(10).Substring(0, 10);
_EDI_ISA.D_704_5 = _Interchange.ISA_05_SenderQualifier.PadRight(2).Substring(0, 2);
_EDI_ISA.D_705_6 = _Interchange.ISA_06_SenderId.PadRight(15).Substring(0,15);
_EDI_ISA.D_704_7 = _Interchange.ISA_07_ReceiverQualifier.PadRight(2).Substring(0, 2);
_EDI_ISA.D_706_8 = _Interchange.ISA_08_ReceiverId.PadRight(15).Substring(0, 15);
_EDI_ISA.D_373_9 = _Interchange.ISA_09_DateReceived.PadRight(6).Substring(0, 6);
_EDI_ISA.D_337_10 = _Interchange.ISA_10_TimeRecieved.PadRight(4).Substring(0, 4);
_EDI_ISA.D_726_11 = _Interchange.ISA_11_RepetitionSeparator.PadRight(1).Substring(0, 1);
_EDI_ISA.D_703_12 = _Interchange.ISA_12_X12Version.PadRight(5).Substring(0, 5);
_EDI_ISA.D_709_13 = _Interchange.ISA_13_UniqueNumberCounter.PadLeft(9,'0');
_EDI_ISA.D_749_14 = _Interchange.ISA_14_AcknoledgementRequested;
_EDI_ISA.D_748_15 = _Interchange.ISA_15_UsageIndicator;
_EDI_ISA.D_701_16 = _Interchange.ISA_16_CompElementSeparator;
_EDI_IEA.D_405_1 = _Interchange.IEA_01_FunctionalGroupCounter.PadLeft(5, '0');
_EDI_IEA.D_709_2 = _Interchange.IEA_02_UniqueNumberCounter.PadLeft(9, '0');
_EDI_Interchange.Iea = _EDI_IEA;
_EDI_Interchange.Isa = _EDI_ISA;
_EDI_GE.D_97_1 = _Interchange.GE_01_TransactionSetCounter.PadLeft(6, '0');
_EDI_GE.D_28_2 = _Interchange.GE_02_UniqueNumberCounter.PadLeft(9, '0');
_EDI_Group.Ge = _EDI_GE;
_EDI_GS.D_479_1 = _Interchange.GS_01.PadRight(2).Substring(0, 2);
_EDI_GS.D_142_2 = _Interchange.GS_02_SenderCode;
_EDI_GS.D_124_3 = _Interchange.GS_03_ReceiverCode;
_EDI_GS.D_29_4 = _Interchange.GS_04_DateReceived.PadRight(6).Substring(0, 8); //datetime.ToString("yyyyMMdd")
_EDI_GS.D_30_5 = _Interchange.GS_05_TimeReceived.PadRight(4).Substring(0, 4); //datetime.ToString("HHmm")
_EDI_GS.D_28_6 = _Interchange.GS_06_UniqueNumberCounter.PadLeft(9,'0');
_EDI_GS.D_455_7 = _Interchange.GS_07_AgencyCode.PadRight(1).Substring(0, 1);
_EDI_GS.D_480_8 = _Interchange.GS_08_X12Version.PadRight(6).Substring(0, 6);
_EDI_Group.Gs = _EDI_GS;
//Set ST Block
_EDI_ST.D_ST01 = X12_ID_143.Item999;
_EDI_ST.D_ST02 = _Group.ST_02_TransactionSetCounter;
_EDI_ST.D_ST03 = X12_ID_1705.Item005010X231A1;
_EDI_999.S_ST = _EDI_ST;
//Set AK1 Block
_EDI_AK1.D_AK101 = _Group.AK_101_FunctionalIdentifier;
_EDI_AK1.D_AK102 = _Group.AK_102_GroupControlNumber;
_EDI_AK1.D_AK103 = _Group.AK_103_VersionIdentifier;
_EDI_999.S_AK1 = _EDI_AK1;
_EDI_AK2.D_AK201 = _Group.AK_201_TransactionSetIdentifier;
_EDI_AK2.D_AK202 = _Group.AK_202_ControlNumber;
_EDI_AK2.D_AK203 = _Group.AK_203_VersionIdentifier;
_EDI_2000.S_AK2 = _EDI_AK2;
//Set IK3 Block
_EDI_IK3.D_IK301 = _Group.IK_301_MissingSegment;
_EDI_IK3.D_IK302 = _Group.IK_302_PositionInTransactionSet;
_EDI_IK3.D_IK304 = X12_ID_620.Item3; // _Group.IK_304_ErrorCode;
_EDI_2100.S_IK3 = _EDI_IK3;
//Set IK5 Block
_EDI_IK5.D_IK501 = X12_ID_717.R;
_EDI_IK5.D_IK502 = X12_ID_618.Item5;
_EDI_2000.S_IK5 = _EDI_IK5;
//Set Lists
_EDI_2100_List.Add(_EDI_2100);
_EDI_2000.G_TS999_2100 = _EDI_2100_List;
_EDI_2000_List.Add(_EDI_2000);
_EDI_999.G_TS999_2000 = _EDI_2000_List;
//AK9 Block
_EDI_AK9.D_AK901 = X12_ID_715.R;//_Group.AK_901_RejectIndicator;
_EDI_AK9.D_AK902 = _Group.AK_902_NumberOfTransactionSets;
_EDI_AK9.D_AK903 = _Group.AK_903_NumberOfTransactionSets;
_EDI_AK9.D_AK904 = _Group.AK_904_NumberAccepted;
_EDI_999.S_AK9 = _EDI_AK9;
//SE Block
_EDI_SE.D_SE01 = _Group.SE_01_SegmentCounter;
_EDI_SE.D_SE02 = _Group.SE_02_TransactionSetCounter;
_EDI_999.S_SE = _EDI_SE;
_EDI_Message = new Message(_EDI_999);
_EDI_Group.Messages.Add(new Message((object)_EDI_999));
_EDI_Interchange.Groups.Add(_EDI_Group);
}
public string GetEdiString()
{
var parsedXml = _EDI_Interchange.ToEdi();
return string.Concat(parsedXml);
}
}
public class DS_M_999_Interchange
{
public string ISA_01_Authorization { get; set; } //default 00
public string ISA_02_AuthInfo { get; set; } //defualt ""
public string ISA_03_SecurityQualifier { get; set; } //default 00
public string ISA_04_Password { get; set; } //default ""
//get from 270/276
public string ISA_05_SenderQualifier { get; set; }
public string ISA_06_SenderId { get; set; }
public string ISA_07_ReceiverQualifier { get; set; }
public string ISA_08_ReceiverId { get; set; }
public string ISA_09_DateReceived { get; set; } //default YYMMDD
public string ISA_10_TimeRecieved { get; set; } //default HHMM
public string ISA_11_RepetitionSeparator { get; set; } //default ^
public string ISA_12_X12Version { get; set; } //default 00501
public string ISA_13_UniqueNumberCounter { get; set; } //will be generated by app
public string ISA_14_AcknoledgementRequested { get; set; } //default 0
public string ISA_15_UsageIndicator { get; set; } //default P
public string ISA_16_CompElementSeparator { get; set; } //default :
//Interchange GS
public string GS_01 { get; set; } //default FA
//from 270/276
public string GS_02_SenderCode { get; set; }
public string GS_03_ReceiverCode { get; set; }
public string GS_04_DateReceived { get; set; } //default CCYYMMDD
public string GS_05_TimeReceived { get; set; } //default HHMM
public string GS_06_UniqueNumberCounter { get; set; } //will be generated by app
public string GS_07_AgencyCode { get; set; } //default "X"
public string GS_08_X12Version { get; set; } //default 00501X231A1
public string GE_01_TransactionSetCounter { get; set; } //number of transaction sets output typically 1
public string GE_02_UniqueNumberCounter { get; set; } //same as GS06
public string IEA_01_FunctionalGroupCounter { get; set; } //number of functional groups typically 1
public string IEA_02_UniqueNumberCounter { get; set; } //same as ISA_13
public DS_M_999_Interchange()
{
ISA_01_Authorization = "00";
ISA_02_AuthInfo = "";
ISA_03_SecurityQualifier = "00";
ISA_04_Password = "";
ISA_09_DateReceived = DateTime.Now.ToString("yyMMdd");
ISA_10_TimeRecieved = DateTime.Now.ToString("HHMM");
ISA_11_RepetitionSeparator = "^";
ISA_12_X12Version = "005010";
ISA_13_UniqueNumberCounter = "1ISA"; //Need to generate/track
ISA_14_AcknoledgementRequested = "0";
ISA_15_UsageIndicator = "P";
ISA_16_CompElementSeparator = ":";
GS_01 = "FA";
GS_04_DateReceived = (DateTime.Now.Year / 100 + 1).ToString() + DateTime.Now.ToString("yyMMdd");
GS_05_TimeReceived = DateTime.Now.ToString("HHMM");
GS_06_UniqueNumberCounter = "1GS06"; //Need to generate/track
GS_07_AgencyCode = "X";
GS_08_X12Version = "005010X231A1";
GE_01_TransactionSetCounter = "1";
GE_02_UniqueNumberCounter = GS_06_UniqueNumberCounter;
IEA_01_FunctionalGroupCounter = "1";
IEA_02_UniqueNumberCounter = ISA_13_UniqueNumberCounter;
}
}
public class DS_M_999_Group
{
public string ST_01_TransactionSetIdentifier { get; set; } //default 999
public string ST_02_TransactionSetCounter { get; set; } //will be generated by app startiing at 0001 (always 0001 in our instance)
public string ST_03_X12Version { get; set; } //default 005010x231a1
//from 270 /276
public string AK_101_FunctionalIdentifier { get; set; }
public string AK_102_GroupControlNumber { get; set; }
public string AK_103_VersionIdentifier { get; set; }
public string AK_201_TransactionSetIdentifier { get; set; }
public string AK_202_ControlNumber { get; set; }
public string AK_203_VersionIdentifier { get; set; }
public string IK_301_MissingSegment { get; set; } //set from x12ParserHelper MissingFields
public string IK_302_PositionInTransactionSet { get; set; } //need to figure this out by parsing incoming edi
public string IK_304_ErrorCode { get; set; } //default 3
public string IK_501_RejectIndicator { get; set; } //default R
public string IK_502_RejectCode { get; set; } //default 5
public string AK_901_RejectIndicator { get; set; } //default R
//from 270/276
public string AK_902_NumberOfTransactionSets { get; set; }
public string AK_903_NumberOfTransactionSets { get; set; }
public string AK_904_NumberAccepted { get; set; } //default 0
public string SE_01_SegmentCounter { get; set; } //#of segments in tx set ST to SE
public string SE_02_TransactionSetCounter { get; set; } //same as ST02
public DS_M_999_Group()
{
ST_01_TransactionSetIdentifier = "999";
ST_02_TransactionSetCounter = "0001";
ST_03_X12Version = "005010X231A1";
IK_304_ErrorCode = "3";
IK_501_RejectIndicator = "R";
IK_502_RejectCode = "5";
AK_901_RejectIndicator = "R";
AK_904_NumberAccepted = "0";
SE_01_SegmentCounter = "1";
SE_02_TransactionSetCounter = ST_02_TransactionSetCounter;
}
}
}
Test Class:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using X12PayloadProcessing;
namespace X12PayloadProcessing.Tests
{
[TestClass]
public class DS_M_999_Tests
{
[TestMethod]
public void DSM999_ToEdiStringShouldBeValid()
{
DS_M_999_Interchange Interchange = new DS_M_999_Interchange();
Interchange.ISA_05_SenderQualifier = "ISA_05_SenderQualifier";
Interchange.ISA_06_SenderId = "SenderID"; //15 space padded
Interchange.ISA_07_ReceiverQualifier = "ISA_06_ReciverQualifier";
Interchange.ISA_08_ReceiverId = "ReceiverID"; //15 space padded
Interchange.GS_02_SenderCode = "GS_02_SenderCode";
Interchange.GS_03_ReceiverCode = "GS_03_ReceiverCode";
DS_M_999_Group Group = new DS_M_999_Group();
Group.AK_101_FunctionalIdentifier = "AK_101_FunctionalIdentifier";
Group.AK_102_GroupControlNumber = "AK_102_GroupControlNumber";
Group.AK_103_VersionIdentifier = "AK_103_VersionIdentifier";
Group.AK_201_TransactionSetIdentifier = "AK_201_TransactionSetIdentifier";
Group.AK_202_ControlNumber = "AK_202_ControlNumber";
Group.AK_203_VersionIdentifier = "AK_203_VersionIdentifier";
Group.IK_301_MissingSegment = "IK_301_MissingSegment";
Group.IK_302_PositionInTransactionSet = "IK_302_PositionInTransactionSet";
Group.AK_902_NumberOfTransactionSets = "AK_902_NumberOfTransactionSets";
Group.AK_903_NumberOfTransactionSets = "AK_903_NumberOfTransactionSets";
DS_M_999 DS_M_999 = new DS_M_999(Group, Interchange);
string ediString = DS_M_999.GetEdiString();
var x = DS_M_999._EDI_Interchange.ToEdi();
Assert.IsNotNull(ediString);
}
}
}
The test will pass as is, but it's not generating the expected EDI output. Obewon Kenobe Please help, your our only hope.
The problem seems to be in the creation of the GS, where in D_480_8 the full version number needs to be set, so that this:
_EDI_GS.D_480_8 = _Interchange.GS_08_X12Version.PadRight(6).Substring(0, 6);
should be changed to this:
_EDI_GS.D_480_8 = _Interchange.GS_08_X12Version;
It's the way the parser determines the correct type - it pulls out the X231A1 part (or the Origin) from the GS instead of the ST or MessageContext.
I found the issue to be lying in the SDK code that got translated into my own code base. The GS.D_480_8 SHOULD NOT be padded as in
_EDI_GS.D_480_8 = _Interchange.GS_08_X12Version.PadRight(6).Substring(0, 6);
The SDK File in question is GRP.cs code:
public void Version(string versionNo)
{
versionNo = versionNo.PadRight(6);
Group.Gs.D_480_8 = versionNo.Substring(0, 6);
}
My particular file was a GS08 version of 12 chars long which when not all present the EDIFabric framework was not handling.
I'm currently testing protobuf-net (latest version), but intermittently I'm getting "Sub-message not read correctly" exception while deserializing. So far there's no apparent pattern to reproduce this error, and the data is always the same.
I googled this error and so far people reported this error only when dealing with big data (>20MB), which I'm not doing.
Can anyone point out whether this is a bug (and if it is, any possible solution to fix/circumvent this?), or am I missing some steps? Below is the code I'm using:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using ProtoBuf;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
const string message = "Cycle {0}: {1:N2} ms - avg: {2:N2} ms - min: {3:N2} - max: {4:N2}";
const int loop = 1000;
var counter = new Stopwatch();
var average = 0d;
var min = double.MaxValue;
var max = double.MinValue;
for (int i = 0;; i++)
{
var classThree = Create();
counter.Reset();
counter.Start();
Parallel.For(0, loop, j =>
{
using (var ms = new MemoryStream())
{
Serializer.Serialize(ms, classThree);
using (var ms2 = new MemoryStream(ms.ToArray()))
{
var des = Serializer.Deserialize<ClassThree>(ms2);
var aaa = des;
}
}
});
counter.Stop();
var elapsed = counter.Elapsed.TotalMilliseconds;
average += elapsed;
min = Math.Min(min, elapsed);
max = Math.Max(max, elapsed);
var currentAverage = average / (i + 1);
Console.Clear();
Console.WriteLine(message, i, elapsed, currentAverage, min, max);
Thread.Sleep(0);
}
}
private static ClassThree Create()
{
var classOne = new ClassSix()
{
// properties
p_i1 = -123,
p_i2 = 456,
p_l1 = -456,
p_l2 = 123,
p_s = "str",
p_f = 12.34f,
p_d = 56.78d,
p_bl = true,
p_dt = DateTime.Now.AddMonths(-1),
p_m = 90.12m,
p_b1 = 12,
p_b2 = -34,
p_c = 'c',
p_s1 = -21,
p_s2 = 43,
p_ts = new TimeSpan(12, 34, 56),
p_id = Guid.NewGuid(),
p_uri = new Uri("http://www.google.com"),
p_ba = new[] { (byte)1, (byte)3, (byte)2 },
p_t = typeof(ClassTwo),
p_sa = new[] { "aaa", "bbb", "ccc" },
p_ia = new[] { 7, 4, 9 },
p_e1 = EnumOne.Three,
p_e2 = EnumTwo.One | EnumTwo.Two,
p_list = new List<ClassFive>(new[]
{
new ClassFive()
{
i = 1,
s = "1"
},
new ClassFive()
{
i = 2,
s = "2"
}
}),
// fields
f_i1 = -123,
f_i2 = 456,
f_l1 = -456,
f_l2 = 123,
f_s = "str",
f_f = 12.34f,
f_d = 56.78d,
f_bl = true,
f_dt = DateTime.Now.AddMonths(-1),
f_m = 90.12m,
f_b1 = 12,
f_b2 = -34,
f_c = 'c',
f_s1 = -21,
f_s2 = 43,
f_ts = new TimeSpan(12, 34, 56),
f_id = Guid.NewGuid(),
f_uri = new Uri("http://www.google.com"),
f_ba = new[] { (byte)1, (byte)3, (byte)2 },
f_t = typeof(ClassTwo),
f_sa = new[] { "aaa", "bbb", "ccc" },
f_ia = new[] { 7, 4, 9 },
f_e1 = EnumOne.Three,
f_e2 = EnumTwo.One | EnumTwo.Two,
f_list = new List<ClassFive>(new[]
{
new ClassFive()
{
i = 1,
s = "1"
},
new ClassFive()
{
i = 2,
s = "2"
}
})
};
var classThree = new ClassThree()
{
ss = "333",
one = classOne,
two = classOne
};
return classThree;
}
}
public enum EnumOne
{
One = 1,
Two = 2,
Three = 3
}
[Flags]
public enum EnumTwo
{
One = 1,
Two = 2,
Three = 4
}
[ProtoContract, ProtoInclude(51, typeof(ClassSix))]
public class ClassOne
{
// properties
[ProtoMember(1)]
public int p_i1 { set; get; }
[ProtoMember(2)]
public uint p_i2 { set; get; }
[ProtoMember(3)]
public long p_l1 { set; get; }
[ProtoMember(4)]
public ulong p_l2 { set; get; }
[ProtoMember(5)]
public string p_s { set; get; }
[ProtoMember(6)]
public float p_f { set; get; }
[ProtoMember(7)]
public double p_d { set; get; }
[ProtoMember(8)]
public bool p_bl { set; get; }
[ProtoMember(9)]
public DateTime p_dt { set; get; }
[ProtoMember(10)]
public decimal p_m { set; get; }
[ProtoMember(11)]
public byte p_b1 { set; get; }
[ProtoMember(12)]
public sbyte p_b2 { set; get; }
[ProtoMember(13)]
public char p_c { set; get; }
[ProtoMember(14)]
public short p_s1 { set; get; }
[ProtoMember(15)]
public ushort p_s2 { set; get; }
[ProtoMember(16)]
public TimeSpan p_ts { set; get; }
[ProtoMember(17)]
public Guid p_id { set; get; }
[ProtoMember(18)]
public Uri p_uri { set; get; }
[ProtoMember(19)]
public byte[] p_ba { set; get; }
[ProtoMember(20)]
public Type p_t { set; get; }
[ProtoMember(21)]
public string[] p_sa { set; get; }
[ProtoMember(22)]
public int[] p_ia { set; get; }
[ProtoMember(23)]
public EnumOne p_e1 { set; get; }
[ProtoMember(24)]
public EnumTwo p_e2 { set; get; }
[ProtoMember(25)]
public List<ClassFive> p_list { set; get; }
// fields
[ProtoMember(26)]
public int f_i1 = 0;
[ProtoMember(27)]
public uint f_i2 = 0;
[ProtoMember(28)]
public long f_l1 = 0L;
[ProtoMember(29)]
public ulong f_l2 = 0UL;
[ProtoMember(30)]
public string f_s = string.Empty;
[ProtoMember(31)]
public float f_f = 0f;
[ProtoMember(32)]
public double f_d = 0d;
[ProtoMember(33)]
public bool f_bl = false;
[ProtoMember(34)]
public DateTime f_dt = DateTime.MinValue;
[ProtoMember(35)]
public decimal f_m = 0m;
[ProtoMember(36)]
public byte f_b1 = 0;
[ProtoMember(37)]
public sbyte f_b2 = 0;
[ProtoMember(38)]
public char f_c = (char)0;
[ProtoMember(39)]
public short f_s1 = 0;
[ProtoMember(40)]
public ushort f_s2 = 0;
[ProtoMember(41)]
public TimeSpan f_ts = TimeSpan.Zero;
[ProtoMember(42)]
public Guid f_id = Guid.Empty;
[ProtoMember(43)]
public Uri f_uri = null;
[ProtoMember(44)]
public byte[] f_ba = null;
[ProtoMember(45)]
public Type f_t = null;
[ProtoMember(46)]
public string[] f_sa = null;
[ProtoMember(47)]
public int[] f_ia = null;
[ProtoMember(48)]
public EnumOne f_e1 = 0;
[ProtoMember(49)]
public EnumTwo f_e2 = 0;
[ProtoMember(50)]
public List<ClassFive> f_list = null;
}
[ProtoContract]
public class ClassSix : ClassOne
{
}
[ProtoContract]
public class ClassTwo
{
}
[ProtoContract]
public interface IClass
{
[ProtoMember(1)]
string ss
{
set;
get;
}
[ProtoMember(2)]
ClassOne one
{
set;
get;
}
}
[ProtoContract]
public class ClassThree : IClass
{
[ProtoMember(1)]
public string ss { set; get; }
[ProtoMember(2)]
public ClassOne one { set; get; }
[ProtoMember(3)]
public ClassSix two { set; get; }
}
[ProtoContract]
public class ClassFour
{
[ProtoMember(1)]
public string ss { set; get; }
[ProtoMember(2)]
public ClassOne one { set; get; }
}
[ProtoContract]
public class ClassFive
{
[ProtoMember(1)]
public int i { set; get; }
[ProtoMember(2)]
public string s { set; get; }
}
}
Updated to rev. 669 and so far haven't encounter the error again. So I'm reporting this as fixed for now.
I'm trying to implement a shopping cart tracking system using pdt with C#.
the trouble i have is finding an example of the paypal succes postback, especially in case of multiple items !
Any help woul be appreciated (some code will be much better :D)!
Thanks
The code below parses PDT response:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.Net;
using System.IO;
using System.Text;
namespace PayPal
{
public static class PaymentDataTransfer
{
private const string AppSetting_Identity = "PayPal.PaymentDataTransfer.Identity";
private const string AppSetting_ServiceUrl = "PayPal.PaymentDataTransfer.ServiceUrl";
public class TransactionStatus
{
public bool Success { get; set; }
public int ErrorCode { get; set; }
public NameValueCollection Parameters { get; set; }
public float PaymentGross { get; set; }
public string Currency { get; set; }
public string Invoice { get; set; }
public PayerInformation Payer { get; set; }
public CartItem[] CartItems;
}
public class PayerInformation
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
public class CartItem
{
public int Number { get; set; }
public string Name { get; set; }
public int Qunatity { get; set; }
public float GrossPrice { get; set; }
}
public static TransactionStatus GetTransactionStatus(string transactionToken)
{
return GetTransactionStatus(transactionToken, false);
}
public static TransactionStatus GetTransactionStatus(string transactionToken, bool sandbox)
{
#if ParsingTest
string response =
#"SUCCESS
mc_gross=1100.00
invoice=334354
protection_eligibility=Eligible
address_status=confirmed
item_number1=1
tax=0.00
item_number2=2
payer_id=DSFSDFSDFSDF
address_street=1+Main+St
payment_date=04%3A13%3A49+Oct+20%2C+2011+PDT
payment_status=Completed
charset=windows-1252
address_zip=95131
mc_shipping=0.00
mc_handling=0.00
first_name=Test
mc_fee=32.20
address_country_code=US
address_name=Test+User
custom=
payer_status=verified
business=yourbusiness%40business.com
address_country=United+States
num_cart_items=2
mc_handling1=0.00
mc_handling2=0.00
address_city=San+Jose
payer_email=payer_email%40business.com
mc_shipping1=0.00
mc_shipping2=0.00
txn_id=0SDFSDFSDFSDFD
payment_type=instant
last_name=User
address_state=CA
item_name1=First+test+item
receiver_email=yourbusiness%40business.com
item_name2=Second+test+item
payment_fee=32.20
quantity1=1
quantity2=1
receiver_id=SDFGDFGDFGDFDFG
txn_type=cart
mc_gross_1=1000.00
mc_currency=USD
mc_gross_2=100.00
residence_country=US
transaction_subject=Shopping+Cart
payment_gross=1100.00";
#else
string authToken = GetAppSetting(AppSetting_Identity, sandbox);
string serviceUrl = GetAppSetting(AppSetting_ServiceUrl, sandbox);
string query = string.Format("cmd=_notify-synch&tx={0}&at={1}", transactionToken, authToken);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = query.Length;
using (var requestStreamWriter = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
requestStreamWriter.Write(query);
requestStreamWriter.Close();
}
string response;
// Do the request to PayPal and get the response
using(StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream()))
{
response = stIn.ReadToEnd();
stIn.Close();
}
#endif
string[] lines = response.Split(new []{"\n", "\r\n"}, StringSplitOptions.None); // splitting up by line breaks
var result = new TransactionStatus
{
Success = lines[0] == "SUCCESS",
Parameters = new NameValueCollection()
};
for(int i=1; i < lines.Length; i++)
{
string line = lines[i];
string[] keyValuePair = lines[i].Split(new [] {'='});
if(keyValuePair.Length == 2)
{
result.Parameters.Add(UrlDecode(keyValuePair[0]), UrlDecode(keyValuePair[1]));
}
else
{
const string errorCodePrefix = "Error:";
if(line.StartsWith(errorCodePrefix))
{
result.ErrorCode = Int32.Parse(line.Substring(errorCodePrefix.Length));
}
}
}
if(result.Success)
{
result.Invoice = result.Parameters["invoice"];
result.Payer = new PayerInformation
{
FirstName = result.Parameters["first_name"],
LastName = result.Parameters["last_name"],
Email = result.Parameters["payer_email"]
};
float paymentGross;
result.PaymentGross = float.TryParse(result.Parameters["mc_gross"],
NumberStyles.Float,
CultureInfo.InvariantCulture,
out paymentGross) ? paymentGross : 0.0f;
result.Currency = result.Parameters["mc_currency"];
int cartItemsNumber;
if (int.TryParse(result.Parameters["num_cart_items"], out cartItemsNumber) && cartItemsNumber > 0)
{
var cartItems = new List<CartItem>();
for(int i=1; i <= cartItemsNumber; i++)
{
cartItems.Add(new CartItem
{
Number = int.Parse(result.Parameters["item_number" + i], CultureInfo.InvariantCulture),
Name = result.Parameters["item_name" + i],
Qunatity = int.Parse(result.Parameters["quantity" + i], CultureInfo.InvariantCulture),
GrossPrice = float.Parse(result.Parameters["mc_gross_" + i], CultureInfo.InvariantCulture)
});
}
result.CartItems = cartItems.ToArray();
}
}
return result;
}
private static string UrlDecode(string encodedText)
{
return Uri.UnescapeDataString(encodedText.Replace("+", " "));
}
private static string GetAppSetting(string settingName, bool sandbox)
{
return ConfigurationManager.AppSettings[settingName + (sandbox ? "_sandbox" : string.Empty)];
}
}
}
The configuration part from web.config:
<appSettings>
.....
<!-- PayPal -->
<add key="PayPal.PaymentDataTransfer.Identity" value="....." />
<add key="PayPal.PaymentDataTransfer.Identity_sandbox" value="....." />
<add key="PayPal.PaymentDataTransfer.ServiceUrl" value="https://www.paypal.com/cgi-bin/webscr" />
<add key="PayPal.PaymentDataTransfer.ServiceUrl_sandbox" value="https://www.sandbox.paypal.com/cgi-bin/webscr" />
</appSettings>
I believe this book has some good examples.
http://www.amazon.com/Beginning-ASP-NET-E-Commerce-2005-ebook/dp/B001JEPVVE/ref=sr_1_2?ie=UTF8&s=digital-text&qid=1268249356&sr=8-2