IsoMessage 8583 XML c# - c#

While executing, I get the error at this location.
XDocument doc = XDocument.Parse(BuildIsoMessage.Properties.Resources.Deneme);//I Get the document from resources in this way.
` GenericPackager packager = new GenericPackager(doc.ToString());`
An unhandled exception of type 'org.jpos.iso.ISOException' occurred in jpos.dll.Additional information: Error reading <!DOCTYPE isopackager PUBLIC "-//jPOS/jPOS Generic Packager DTD 1.0//EN" "http://jpos.org/dtd/generic-packager-1.0.dtd"[]>
I am trying to build an ISO Message in c#. I converted Jar files into one dll file and using some of the namespaces
using org.jpos.util;
using org.jpos.iso;
using org.jpos.iso.channel;
using org.jpos.iso.packager;
however I can not pack my xml file, it throws an error.
https://github.com/jpos/jPOS/blob/master/jpos/src/main/resources/packager/iso87ascii.xml

Jpos dll worked fine when provided path like below
GenericValidatingPackager packager = new GenericValidatingPackager();
packager.readFile("c:/isoxml/iso8583binary.xml");

This is too simple to use a 3rd party dll. Use xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string xmlHeader =
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
"<!DOCTYPE isopackager PUBLIC" +
" \"-//jPOS/jPOS Generic Packager DTD 1.0//EN\"" +
" \"http://jpos.org/dtd/generic-packager-1.0.dtd\" >" +
"<!-- ISO 8583:1987 (ASCII) field descriptions for GenericPackager -->" +
"<isopackager>" +
"</isopackager>";
//<isofield
XDocument doc = XDocument.Parse(xmlHeader);
XElement isoPackager = doc.Descendants("isopackager").FirstOrDefault();
List<IsoField> isoFields = new List<IsoField>() {
new IsoField() { id= 0, length= 4, name="MESSAGE TYPE INDICATOR", cClass = "org.jpos.iso.IFA_NUMERIC"},
new IsoField() { id= 1, length= 16, name="BIT MAP", cClass= "org.jpos.iso.IFA_BITMAP"},
new IsoField() { id= 2, length= 19, name="PAN - PRIMARY ACCOUNT NUMBER", cClass= "org.jpos.iso.IFA_LLNUM"}
};
foreach (IsoField isofield in isoFields)
{
isoPackager.Add(new XElement("isofield", new object[] {
new XElement("id", isofield.id),
new XElement("length", isofield.length),
new XElement("name", isofield.name),
new XElement("class", isofield.cClass)
}));
}
doc.Save(FILENAME);
}
}
public class IsoField
{
public int id {get; set;}
public int length { get; set; }
public string name { get; set; }
public string cClass { get; set; }
}
}

Related

Is there a recommended way of writing the contents of variables to a text file?

As a tutorial project I had to create a Coffee Machine Simulator using c#. I have completed this project successfully, but I would like the contents of the variables to be written to a file so that the user does not need to set it up again. I have tried this by attempting the demo project from Microsoft:
using System;
using System.Linq;
using System.IO;
using System.Reflection.Metadata;
using System.Text;
namespace TestingCode
{
class Program
{
public static void Main()
{
string path = "Test.txt";
try
{
// Create the file, or overwrite if the file exists.
using (FileStream fs = File.Create(path))
{
Console.WriteLine("Enter a string:");
string input = Console.ReadLine();
byte[] info = new UTF8Encoding(true).GetBytes(input);
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
// Open the stream and read it back.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}
This code successfully runs and writes the value of the user input to a text file. Please can anybody help me write the variables into a text file and read from them as well.
Thanks,
KINGAWESOME266
Edit: you can install Newtonsoft.Json by using nugget package manager
The fastest and easiest way I can think of is using Newtonsoft.Json to serialize data
Create a class to store your variables:
Let's say we have this Model class which stores our variables
public class Model
{
public int Variable1;
public string Variable2;
public List<string> Variable3;
}
Here is our object that we want to serialize:
Model m = new Model()
{
Variable1 = 1,
Variable2 = "test test",
Variable3 = new List<string>() { "list element 1 ", "list element 2", "list element 3"}
};
To serialize this object call JsonConvert.SerializeObject with your object as param
The output of this is a json string, in our case:
{"Variable1":1,"Variable2":"test test","Variable3":["list element 1 ","list element 2","list element 3"]}
var serializedData = JsonConvert.SerializeObject(m);
Save the string to a file and read it back again
File.WriteAllText("serialized.txt", serializedData);
var loadedData = File.ReadAllText("serialized.txt");
Convert back the read string to an object by calling JsonConvert.DeserializeObject(yourObject);
var loadedObject = JsonConvert.DeserializeObject<Model>(loadedData);
Complete example:
static void Main(string[] args)
{
Model m = new Model()
{
Variable1 = 1,
Variable2 = "test test",
Variable3 = new List<string>() { "list element 1 ", "list element 2", "list element 3" }
};
var serializedData = JsonConvert.SerializeObject(m);
File.WriteAllText("serialized.txt", serializedData);
var loadedData = File.ReadAllText("serialized.txt");
var loadedObject = JsonConvert.DeserializeObject<Model>(loadedData);
}

During Xml deserialization, matrix is returning null

Got lots of trials to deserialize the following XML file:
<?xml version="1.0" encoding="UTF-8"?>
<map version="1.2" tiledversion="1.3.1" orientation="orthogonal" renderorder="right-down" compressionlevel="0" width="80" height="50" tilewidth="16" tileheight="16" infinite="0" nextlayerid="2" nextobjectid="1">
<tileset firstgid="1" name="TilesetSA" tilewidth="16" tileheight="16" tilecount="4000" columns="80">
<image source="../../TilesetSA.png" width="1280" height="800"/>
</tileset>
<layer id="1" name="Walls" width="80" height="50">
<data encoding="csv">
3,3,3,3,3,3,3,3,3,3,3,3,3,3,
3,81,81,81,81,81,81,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,3,3,3,3,3,3,3,3,3,3,3,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,
</data>
</layer>
</map>
I don't have the opportunity to change the xml file, it must stay as is.
I Managed to retreive all attributes for "map", "tileset" and "image", but in the "layer" element, in can only retreive the attributes (id, name, width, height), the data element always remains null.
I created dedicated classes for "map", "tileset", "layer", "image" and "map".
Would anyone suggest me any code to solve this "null result" issue?
Use following xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication159
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
string dataStr = (string)doc.Descendants("data").FirstOrDefault();
int[][] results = dataStr.Split(new char[] {'\n'}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(y => int.Parse(y)).ToArray()).ToArray();
}
}
}
My code is as follow:
public virtual void WriteSaveXmlData(string pPath, int pRoom, bool pNewGame, int pX, int pY)
{
//xml save serialization
XmlSaving XmlGameSave = new XmlSaving();
XmlGameSave.SaveRootPath = pPath;
XmlGameSave.SavedCurrentRoom = pRoom;
XmlGameSave.XmlIsNewGame = pNewGame;
XmlGameSave.XHero = pX;
XmlGameSave.YHero = pY;
XmlSerializer xs = new XmlSerializer(typeof(XmlSaving));
using (StreamWriter wr = new StreamWriter(GameRound.GameSaveRootPath + GameRound.SaveFileName))
{
xs.Serialize(wr, XmlGameSave);
}
}
public virtual XmlSaving ReadSaveXmlData()
{
//xml save deserialization
XmlSerializer xs = new XmlSerializer(typeof(XmlSaving));
using (StreamReader rd = new StreamReader(GameRound.GameSaveRootPath + GameRound.SaveFileName))
{
XmlSaving XmlGameSave = xs.Deserialize(rd) as XmlSaving;
return XmlGameSave;
}
}
public virtual XmlMap ReadXmlMapData(string pPath, int RoomNumber)
{
XmlMap ReadTmxData = new XmlMap();
XmlSerializer TmxXmlMap = new XmlSerializer(typeof(XmlMap));
using (StreamReader rd = new StreamReader(pPath + #"P1\RoomMapSaphir0" + RoomNumber + ".tmx"))
{
ReadTmxData = TmxXmlMap.Deserialize(rd) as XmlMap;
return ReadTmxData;
}
}

How to know class type when reading data from file?

I have 3 classes. 'Product' is the base class. 'Book' and 'Software' is the class that I inherit to 'Product' class. First I write it to file and I want to read it back to know whether it 'Book' or 'Software' class. Could anyone help me please?
Here is my code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
namespace ProductMainten
{
public class ProductDB
{
private const string dir = #"C:\C# 2012 Soben\Files\";
private const string path = dir + "ProductsCh14.txt";
public static List<Product> GetProducts()
{
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
StreamReader textIn = new StreamReader(
new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));
List<Product> products = new List<Product>();
while (textIn.Peek() != -1)
{
string row = textIn.ReadLine();
string[] columns = row.Split('|');
Product product = new Product();
product.Code = columns[0];
product.Description = columns[1];
product.Price = Convert.ToDecimal(columns[2]);
products.Add(product);
}
textIn.Close();
return products;
}
public static void SaveProducts(List<Product> products)
{
StreamWriter textOut = new StreamWriter(
new FileStream(path, FileMode.Append, FileAccess.Write));
foreach (Product product in products)
{
if(product.GetType().Name == "Book")
{
WriteBook((Book)product, textOut);
}
else if(product.GetType().Name == "Software")
{
WriteSoftware((Software)product, textOut);
}
}
textOut.Close();
}
private static void WriteBook(Book product, StreamWriter textOut)
{
WriteBase(product, textOut);
textOut.Write(product.Author + "\n");
}
private static void WriteSoftware(Software product, StreamWriter textOut)
{
WriteBase(product, textOut);
textOut.Write(product.Version + "\n");
}
private static void WriteBase(Product product, StreamWriter textOut)
{
textOut.Write(product.Code + "|");
textOut.Write(product.Description + "|");
textOut.Write(product.Price + "|");
}
}
}
This is the code and for writing to file that's ok
It is not possible to determine the type from what I see, what you do is you write something like this:
MyCode|MyDescription|MyPrice|MyAdditionalProperty
There is no way you can detect type from this string unless there are some additional rules imposed on the inherited classes properties.
What you can do is add this information as your first element:
textOut.Write(product.GetType() + "|"); // You can write a switch instead to write your own string instead of a full name
Then when you read your data you first read the type moniker, after you do that you write a switch to create an instance of your class or use reflection if you write the full type.
P.S. I would suggest to look in some standardized libraries (or built-in methods) to do the serialization/deserialization instead of writing it yourself unless you have a good reason not not.

Evaluating equations during "new EXlement"

The snippet below isn't summing the variables (int)winTemp and playerWIn. I've verified that both variables are assigned the correct value by printing to screen before calling createXML(). My theory is that you cannot evaluate equations while creating new XELEMENT's. Can anyone verify this?
new XElement("playerWin", (int)winTemp + playerWin),
If I do it outside of XElement, like the commented lines in saveXML(), it works as intended.
If the file did not exist - Excepted XML output should be Wins=10, Loss=1, Tie=0.
If the file was existed - Excepted XML output should be Wins=20, Loss=2, Tie=0.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
namespace Testing_LINQ_to_XML
{
class Program
{
static void Main()
{
Player p = new Player();
p.readXML();
p.toScreen();
p.saveXML();
p.readXML();
p.toScreen();
p.Exit();
}
}
public class Player
{
public string path;
public string playerName;
public int playerWin = 10;
public int playerLoss = 1;
public int playerTie = 0;
public int winTemp;
public int lossTemp;
public int tieTemp;
public Player()
{
Console.WriteLine("Enter player Name...");
playerName = Console.ReadLine();
Console.WriteLine("n: " + playerName);
getPath();
Console.WriteLine("p: " + path);
Console.ReadLine();
}
public string getPath()
{
path = (#"..\XML Saves\" + playerName + ".xml");
return path;
}
public void toScreen()
{
Console.WriteLine("\nYour Record Is:\n");
Console.WriteLine("Wins: " + playerWin);
Console.WriteLine("Losses: " + playerLoss);
Console.WriteLine("Ties: " + playerTie);
}
public void saveXML()
{
if (File.Exists(path))
{
readXML();
File.Delete(path);
//playerWin = (int)winTemp;
//playerLoss = (int)lossTemp;
//playerTie = (int)tieTemp;
createFile();
}
else
{
createFile();
}
}
public void createFile()
{
XDeclaration _obj = new XDeclaration("1.0", "utf-8", "");
XNamespace gameSaves = "gameSaves";
XElement fileNew = new XElement("Root",
new XElement("Player",
new XElement("playerName", playerName),
new XElement("Stats",
new XElement("playerWin", (int)winTemp + playerWin),
new XElement("playerLoss", (int)lossTemp + playerLoss),
new XElement("playerTie", (int)tieTemp + playerTie))));
fileNew.Save(path);
Console.WriteLine("Save created: " + path);
}
public void readXML()
{
if (File.Exists(path))
{
var winTemp = new XElement("playerWin", playerWin);
var lossTemp = new XElement("playerLoss", playerLoss);
var tieTemp = new XElement("playerTie", playerTie);
}
else
{
Console.WriteLine("\nYou don't have any stats to show yet. Get playing!!!");
}
}
public void Exit()
{
Console.WriteLine("Press any key to exit.");
Console.ReadLine();
}
}
}
XML output:
<Root>
<Player>
<playerName>Name</playerName>
<Stats>
<playerWin>10</playerWin>
<playerLoss>1</playerLoss>
<playerTie>0</playerTie>
</Stats>
</Player>
</Root>
The locally scoped winTemp variable is hiding the instance variable (inside readXML() method). Thus winTemp instance variable does not get set at all and holds the default value, i.e. 0, by the time of addition.

Using C#, how do I set a Rally weblink field?

Here's a screenshot of the field I'm trying to update:
How do I update the URL field?
WebLink type fields consist of two parts: LinkID and DisplayString. In order to set a LinkID (which corresponds to the variable ${id} in your screenshot, a DisplayString needs also to be set to an empty string.
Here is a full code example that uses Rally .NET REST toolkit:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Rally.RestApi;
using Rally.RestApi.Response;
namespace aRestApp_CollectionOfTasks
{
class Program
{
static void Main(string[] args)
{
//Initialize the REST API
RallyRestApi restApi;
restApi = new RallyRestApi("user#co.com", "secret", "https://rally1.rallydev.com", "v2.0");
//Set our Workspace and Project scopings
String workspaceRef = "/workspace/1111"; //please replace this OID with an OID of your workspace
String projectRef = "/project/2222"; //please replace this OID with an OID of your project
bool projectScopingUp = false;
bool projectScopingDown = true;
Request storyRequest = new Request("Defect");
storyRequest.Workspace = workspaceRef;
storyRequest.Project = projectRef;
storyRequest.ProjectScopeUp = projectScopingUp;
storyRequest.ProjectScopeDown = projectScopingDown;
storyRequest.Fetch = new List<string>()
{
"Name",
"_ref",
"c_JiraLink"
};
storyRequest.Query = new Query("FormattedID", Query.Operator.Equals, "DE170");
QueryResult queryStoryResults = restApi.Query(storyRequest);
foreach (var s in queryStoryResults.Results)
{
Console.WriteLine(" Name: " + s["Name"] + " JiraLink's DisplayString: " + s["c_JiraLink"]["DisplayString"] + " JiraLink's LinkID: " + s["c_JiraLink"]["LinkID"]);
DynamicJsonObject toUpdate = new DynamicJsonObject();
DynamicJsonObject myLink = new DynamicJsonObject();
myLink["LinkID"] = "NM-3";
myLink["DisplayString"] = "";
toUpdate["c_JiraLink"] = myLink;
OperationResult updateResult = restApi.Update(s["_ref"], toUpdate);
}
}
}
}
Note that this is not different from a more general example of setting LinkID of a WebLink type of filed using a browser's REST client.
Method: POST
URL:
https://rally1.rallydev.com/slm/webservice/v2.0/defect/3807704995?key=abc123...
Request Body:
{
"defect":
{
"c_JiraLink":{
"DisplayString":"",
"LinkID":"NM-2"
}
}
}

Categories

Resources