How to read/write objects to xml? - c#

I am trying to make a XML Parser of sort that reads in chunks of a class object into a file and should also be able to edit the same.
The class structure is as follows
[Serializable]
public class Service
{
public enum ServiceStatus { ACTIVE, INACTIVE, SUSPENDED };
//Unique identifier for a service
string _Id;
public string Id
{ get{ return _Id;}
set{ _Id = value;}
}
//Name of the service, for reference of the client
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
//URI where the service is hosted
string _uri;
public string Uri
{
get { return _uri; }
set { _uri = value; }
}
//The state of the service
ServiceStatus _status;
public ServiceStatus Status
{
get { return _status;}
set { _status = value; }
}
//the categories contained in the service instance
public ICollection<Category> Categories;
//collection of users/clients who can access this service
public ICollection<Client> Clients;
public Service()
{
_Id = null;
_name = null;
_uri = null;
_status = ServiceStatus.ACTIVE;
Categories = new List<Category>();
Clients = new List<Client>();
}
}
The Category class is as follows
public class Category
{
//Unique identifier for a category
string _Id;
public string Id
{
get { return _Id; }
set { _Id = value; }
}
//Name of the category, for reference of the client
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
//URI where the category is hosted
string _uri;
public string Uri
{
get { return _uri; }
set { _uri = value; }
}
//Collection of pulses in this category
public ICollection<Pulse> Pulses;
public Category()
{
_Id = null;
_name = null;
_uri = null;
Pulses = new List<Pulse>();
}
}
The pulse class is a similar class with just id and name.
What would be the best way to read/write such objects in an xml file. The operation is read heavy and I would like to have the values read as accessible as possible, possible as array indexed or as a dictionary, but any form is fine.
Kindly suggest the simplest way. I am overwhelmed by the number of classes for XML in c#

What about converting it into DataSet and the performing your operations?
XmlTextReader.ReadXml(reader);

DataSet ds = new DataSet();
ds.ReadXml(fileNamePath);
This will convert all your XML into DataSet. After converting XML into DataSet you can perform whatever operation you would like to do.

Related

Neo4jClient Node/Relationship Class conventions

Is there a standard naming convention for the properties/methods of a node/relationship class when working with Neo4jClient?
I'm following this link Neo4jClient - Retrieving relationship from Cypher query to create my relationship class
However, there are certain properties of my relationship which i can't get any value despite the relationship having it. While debugging my code, i realized certain properties was not retrieved from the relationship when creating the relationship object.
this is my relationship class
public class Creates
{
private string _raw;
private int _sourcePort;
private string _image;
private int _DestinationPort;
private int _eventcode;
private string _name;
private string _src_ip;
private int _src_port;
private string _dvc;
private int _signature_ID;
private string _dest_ip;
private string _computer;
private string _sourceType;
private int _recordID;
private int _processID;
private DateTime _time;
private int _dest_port;
public string Raw { get { return _raw; } set { _raw = value; } }
public int SourcePort { get { return _sourcePort; } set { _sourcePort = value; } }
public string Image { get { return _image; } set { _image = value; } }
public int DestinationPort { get { return _DestinationPort; } set { _DestinationPort = value; } }
public int Eventcode { get { return _eventcode; } set { _eventcode = value; } }
public string Name { get { return _name; } set { _name = value; } }
public string Src_ip { get { return _src_ip; } set { _src_ip = value; } }
public int Src_port { get { return _src_port; } set { _src_port = value; } }
public string DVC { get { return _dvc; } set { _dvc = value; } }
public int Signature_ID { get { return _signature_ID; } set { _signature_ID = value; } }
public string Dest_ip { get { return _dest_ip; } set { _dest_ip = value; } }
public string Computer { get { return _computer; } set { _computer = value; } }
public string SourceType { get { return _sourceType; } set { _sourceType = value; } }
public int RecordID { get { return _recordID; } set { _recordID = value; } }
public int ProcessID { get { return _processID; } set { _processID = value; } }
public DateTime Indextime { get { return _time; } set { _time = value; } }
public int Dest_port { get { return _dest_port; } set { _dest_port = value; } }
}
This is another class
public class ProcessConnectedIP
{
public Neo4jClient.RelationshipInstance<Pivot> bindto { get; set; }
public Neo4jClient.Node<LogEvent> bindip { get; set; }
public Neo4jClient.RelationshipInstance<Pivot> connectto { get; set; }
public Neo4jClient.Node<LogEvent> connectip { get; set; }
}
This is my neo4jclient query to get the relationship object
public IEnumerable<ProcessConnectedIP> GetConnectedIPs(string nodeName)
{
try
{
var result =
this.client.Cypher.Match("(sourceNode:Process{name:{nameParam}})-[b:Bind_IP]->(bind:IP_Address)-[c:Connect_IP]->(connect:IP_Address)")
.WithParam("nameParam", nodeName)
.Where("b.dest_ip = c.dest_ip")
.AndWhere("c.Image=~{imageParam}")
.WithParam("imageParam", $".*" + nodeName + ".*")
.Return((b, bind, c, connect) => new ProcessConnectedIP
{
bindto = b.As<RelationshipInstance<Creates>>(),
bindip = bind.As<Node<LogEvent>>(),
connectto = c.As<RelationshipInstance<Creates>>(),
connectip = connect.As<Node<LogEvent>>()
})
.Results;
return result;
}catch(Exception ex)
{
Console.WriteLine("GetConnectedIPs: Error Msg: " + ex.Message);
return null;
}
}
This is the method to read the results
public void MyMethod(string name)
{
IEnumerable<ProcessConnectedIP> result = clientDAL.GetConnectedIPs(name);
if(result != null)
{
var results = result.ToList();
Console.WriteLine(results.Count());
foreach (ProcessConnectedIP item in results)
{
Console.WriteLine(item.Data.Src_ip);
Console.WriteLine(item.bindto.StartNodeReference.Id);
Console.WriteLine(item.bindto.EndNodeReference.Id);
Console.WriteLine(item.connectto.StartNodeReference.Id);
Console.WriteLine(item.connectto.EndNodeReference.Id);
Node<LogEvent> ans = item.bindip;
LogEvent log = ans.Data;
Console.WriteLine(log.Name);
Node<LogEvent> ans1 = item.connectip;
LogEvent log1 = ans1.Data;
Console.WriteLine(log1.Name);
}
}
}
Somehow, i'm only able to populate the relationship object with src_ip/src_port/dest_ip/dest_port values. the rest are empty.
Is there any possible reason why? I've played with upper/lower cases on the properties names but it does not seem to work.
This is the section of the graph im working with
This is the relationship properties sample:
_raw: Some XML dataSourcePort: 49767Image: C:\Windows\explorer.exeDestinationPort: 443EventCode: 3Name: Bind
IPsrc_ip: 172.10.10.104dvc: COMPUTER-NAMEsrc_port:
49767signature_id: 3dest_ip: 172.10.10.11Computer:
COMPUTRE-NAME_sourcetype:
XmlWinEventLog:Microsoft-Windows-Sysmon/OperationalRecordID:
13405621ProcessId: 7184_time: 2017-08-28T15:15:39+08:00dest_port: 443
I'm not entirely sure how your Creates class is ever populated, in particular those fields - as your Src_port property doesn't match the src_port in the sample you provided (case wise).
I think it's probably best to go back to a super simple version. Neo4jClient will map your properties to the properties in the Relationship as long as they have the same name (and it is case-sensitive).
So start with a new Creates class (and use auto properties - it'll make your life a lot easier!)
public class Creates
{
public string Computer { get; set; }
}
Run your query with that and see if you get a result, then keep on adding properties that match the name and type you expect to get back (int, string etc)
It seems that i have to give neo4j node/relationship property names in lowercase and without special characters at the start of the property name, in order for the above codes to work.
The graph was not created by me at the start thus i had to work on it with what was given. I had to get the developer who created the graph to create the nodes with lowercases in order for the above to work.

Filtering mongodb data

I have the following model:
Base class:
public abstract class Identifiable{
private ObjectId id;
private string name;
protected Identifiable(){
id = ObjectId.GenerateNewId();
}
[BsonId]
public ObjectId Id{
get { return id; }
set { id = value; }
}
[BsonRequired]
public string Name{
get { return name; }
set { name = value; }
}
}
The name is unique.
A channel class
public class Channel : Identifiable{
private DateTime creationDate;
private string url;
private DailyPrograming dailyPrograming;
public DailyPrograming DailyPrograming{
get { return dailyPrograming; }
set { dailyPrograming = value; }
}
public DateTime CreationDate{
get { return creationDate; }
set { creationDate = value; }
}
public string Url{
get { return url; }
set { url = value; }
}
}
Daily programs. The name property is the date stored as ddMMyyyy:
public class DailyPrograming : Identifiable{
public DailyPrograming(){
DailyPrograms = new List<Program>(30);
}
public IList<Program> DailyPrograms { get; set; }
}
The programs:
public class Program : Identifiable{
private DateTime programDate;
private string category;
private string description;
public DateTime ProgramDate{
get { return programDate; }
set { programDate = value; }
}
public string Category{
get { return category; }
set { category = value; }
}
public string Description{
get { return description; }
set { description = value; }
}
}
Now, I want to filter the program of certain channel for specific date using:
public DailyPrograming GetProgramsForDate(string channelId, string prgDate){
ObjectId id = new ObjectId(channelId);
IMongoQuery query = Query.And(Query<Channel>.EQ(c => c.Id, id),
Query<DailyPrograming>.EQ(dp => dp.Name, prgDate));
var result = Database.GetCollection<DailyPrograming>(CollectionName).Find(query).FirstOrDefault();
return result;
}
But it never returns the existing data. How to retrieve the programings of a channel for a date?
-
var builder = Builders<BsonDocument>.Filter;
var filt = builder.Eq("Price", "9.20")
& builder.Eq("ProductName", "WH-208");
var list = await collection.Find(filt).ToListAsync();
We can use & instead of $and. See this post, for another example.
According to your sample I used id = "54c00c65c215161c7ce2a77c" and prgDate = "2212015"
then I changed the query to this:
var collection = database.GetCollection<Channel>("test6");
var id = new ObjectId("54c00c65c215161c7ce2a77c");
var query = Query.And(Query<Channel>.EQ(c => c.Id, id), Query<Channel>.EQ(c => c.DailyPrograming.Name, "2212015"));
var result = collection.Find(query).FirstOrDefault();
this query works fine
Some point:
Your collection type is Chanel not DailyPrograming
When your collection is Chanel you have to use Query<Channel> and query nested DailyPrograming via Query<Channel>.EQ(c => c.DailyPrograming.Name, "2212015")

Sending an object throug a webservice and retrieve data in asp.net or silverlight

I am using silverlight to develop a windows gadget,I need to call a asp.net web service and which is return an object with some data.
I want to receive that object and show data.
My codes are below
Web services code.
[WebMethod]
public userdata LogIn(string username,string user_password)
{
return udata;
}
return new userdata();
}
}
My custom class code is
public class userdata
{
string name;
public string Name
{
get { return name; }
set { name = value; }
}
string userName;
public string UserName
{
get { return userName; }
set { userName = value; }
}
string department;
public string Department
{
get { return department; }
set { department = value; }
}
string designation;
public string Designation
{
get { return designation; }
set { designation = value; }
}
string email;
public string Email
{
get { return email; }
set { email = value; }
}
string mobile;
public string Mobile
{
get { return mobile; }
set { mobile = value; }
}
string ip;
public string Ip
{
get { return ip; }
set { ip = value; }
}
string id;
public string Id
{
get { return id; }
set { id = value; }
}
}
it returns
<userdata>
<Name>Asik</Name>
<UserName>asikcse</UserName
><Department>technical</Department>
<Designation>Software Programmer</Designation>
<Id>1</Id>
</userdata>
And in the end of my project I add web references as that references but havent any solution to this.
LoginServiceSoapClient login = new LoginServiceSoapClient();
login.LogInCompleted+=new EventHandler<LogInCompletedEventArgs>(login_LogInCompleted);
login.LogInAsync(log._nameText, log._surnameText);
}
void login_LogInCompleted(object sender, LogInCompletedEventArgs e)
{
How can I retrieve this object returned by webmethod
}
So you will need to create a class in the silverlight application to hold the data, I suggest just copying the userdata class. Then you will need to make an request to that endpoint to get the data. This can be done using the WebClient class. Then use the DataContractSerializer to turn the xml into an object. Here is an example:
WebClient webClient = new WebClient();
var data = webClient.DownloadString("<your endpoint>"); //You can do this async too
var serializer = new DataContractSerializer(typeof(UserData));
Byte[] bytes = Encoding.Unicode.GetBytes(data);
UserData userData;
using (MemoryStream stream = new MemoryStream(bytes))
{
userData = serializer.ReadObject(stream) as UserData;
}
There are some smarter ways to do this.

Some fields are empty after deserialization in Silverlight project

I have a problem with deserialization in my silverlight project. I have class Obj with this methods and variables.
public class Obj
{
private string _name;
private Uri _iconUri;
private string _stringUri;
private List<ObjItem> _items = new List<ObjItem>();
public List<ObjItem> Items
{
get { return _items; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public Uri IconUri
{
get
{
return _iconUri;
}
}
public string StringUri { get { return _stringUri; } }
public int Count
{
get { return _items.Count; }
}
public Obj(string name,string uriString = null)
{
_name = name;
if (uriString == null)
{
_iconUri = null;
}
else
{
_iconUri = new Uri(uriString, UriKind.Relative);
}
_stringUri = uriString;
}
// for deserialization
public Obj()
{
}
}
Before serialization all fields are not empty!
After deserialization all fields are not empry except _iconUri and _stringUri fields.
Why is it happened?
I'll be waiting for your replies.
Thank you!
Those two don't have setters. Silverlight has a restricted security model, where you cant can't cheat by accessing private fields; only public members can be accessed. So: add public setters to those properties if you want them to work with most serializers on SL.
To be specific: _name is being set by the Name setter, and _items is being set in the constructor via the field-initializer.

NHibernate.QueryException ActiveRecord

[ActiveRecord]
public class Category
{
private int _id;
private string _name;
private Category _category;
[PrimaryKey(PrimaryKeyType.HiLo, "id", Params = "max_lo=9")]
public long Id
{
get { return _id; }
protected internal set { _id = value; }
}
[Property]
public string Name
{
get { return _name; }
set { _name = value; }
}
[BelongsTo("ParentCategoryId")]
public Category ParentCategory
{
get { return _category;}
set { _category = value; }
}
}
Table is correctly generated in the database and data can be insterted without any problems
But when I'm running
var criteria = DetachedCriteria.For<Category>
.Add(Restrictions.Eq("ParentCategory.ParentCategoryId", testCategory.id));
Assert.That(m_repository.FindAll(criteria).Length, Is.EqualTo(1));
I'm reciving QueryException
`NHibernate.QueryException : could not
resolve property:
ParentCategory.ParentCategoryId'
Any idea?
You are fetching the ParentCategory property of a Category, which is itself a Category. Your DetachedCriteria should be:
var criteria = DetachedCriteria.For<Category>()
.Add(Restrictions.Eq("ParentCategory.Id",
testCategory.id));

Categories

Resources