Can't serialize custom class - c#

I'm pretty new with Xamarin and I'm trying to make an app for Android/iOS. I'm trying to send over a class with a putExtra, so I tried to make the class Serializable by adding the ISerializable interface, but whenever I try to do that I need to implement a Handle() and Dispose() method. I'm not sure what to do with those methods, so they have a NotImplementedException.
When I try to go the next activity I get the NotImplementedException (which most likely comes from the handle or the dispose). I would like to know if I'm doing something wrong with the implementation of my class.
Here is the Event class (which I try to send over to the next Activity):
public class Event : Object, ISerializable
{
private long id;
private string name;
private string description;
private double latitude = 0;
private double longitude = 0;
private User author;
private List<User> participants;
private List<EventDate> eventDates;
public Event(long id, string name, string description, double latitude, double longitude, User author, List<User> participants, List<EventDate> eventDates)
{
this.id = id;
this.name = name;
this.description = description;
this.latitude = latitude;
this.longitude = longitude;
this.author = author;
this.participants = participants;
this.eventDates = eventDates;
}
public Event(long id, string name, string description, User author)
{
this.id = id;
this.name = name;
this.description = description;
this.author = author;
this.participants = new List<User>();
this.eventDates = new List<EventDate>();
}
public long Id
{
get { return id; }
}
public string Name
{
get { return name; }
}
public string Description
{
get { return description; }
}
public double Latitude
{
get { return latitude; }
}
public User Author
{
get { return author; }
}
public List<User> Participants
{
get { return participants; }
}
public List<EventDate> EventDates
{
get { return eventDates; }
}
public IntPtr Handle
{
get
{
throw new NotImplementedException();
}
}
public EventDate getBestDate()
{
EventDate bestDate = null;
foreach (EventDate date in eventDates)
{
if (bestDate == null || date.AvailableUsers.Count > bestDate.AvailableUsers.Count)
{
bestDate = date;
}
}
return bestDate;
}
public void addParticipant(User participant)
{
this.participants.Add(participant);
}
public void Dispose()
{
throw new NotImplementedException();
}
}
This class is in the (Portable) project and not in the .Droid project, since I also need it in iOS.
Could someone please tell me what I'm doing wrong or maybe suggest an alternative?
Thanks in advance.

You have change ISerializable to Java.IO.ISerializable.
I have Created this way
class MySerializable : Object, Java.IO.ISerializable
{
public string Value {get; private set;}
public MySerializable (IntPtr handle, JniHandleOwnership transfer)
: base (handle, transfer)
{
}
public MySerializable ()
{
}
public MySerializable (string value)
{
Value = value;
}
}
for more detail visit this :
https://developer.xamarin.com/api/type/Java.IO.ISerializable/
Hope this will help you.

Related

how to create an update method in c#

Im trying to create a method to update an input string with another input string. for example you set accountHoldername to james then you enter another acountHolderNAme matty. the update accountHolderName method should return back matty
public class BankAccount
{
private String accountHolderName;
public BankAccount ( double balance, String accountHolderName, long accountNumber)
{
this.accountHolderName = accountHolderName;
}
public long AccountNumebr
{
get
{
return accountNumber;
}
set
{
this.accountNumber = value;
}
}
public String AccountHolderName
{
get
{
return accountHolderName;
}
set
{
this.accountHolderName = value;
}
}
public double Balance
{
get
{
return balance;
}
set
{
this.balance = value;
}
}
public String UpdateAccountHolderName()
{
}
}
If you really want that method, use private setters for your property:
public class BankAccount
{
public string AccountHolderName { get; private set; }
//Note there's really no need for a return value here
public void UpdateAccountHolderName(string newAccountHolderName)
{
AccountHolderName = newAccountHolderName;
}
}
Granted, this is functionally equivalent to:
public class BankAccount
{
public string AccountHolderName { get; set; }
}
An update method makes more sense here if you're updating multiple properties with it.
Edit
You can also do this if you really want:
public class BankAccount
{
public string AccountHolderName { get; private set; }
public string UpdateAccountHolderName(string newAccountHolderName)
{
AccountHolderName = newAccountHolderName;
return AccountHolderName;
}
}
Assuming you meant to have it so that you couldn't set the various properties on the Bank Account publicly then it would look something like this:
public class BankAccount
{
private string accountHolderName;
private long accountNumber;
private double balance;
public BankAccount (double balance, String accountHolderName, long accountNumber)
{
this.accountHolderName = accountHolderName;
this.accountNumber = accountNumber;
this.balance = balance;
}
public long AccountNumber
{
get
{
return accountNumber;
}
}
public string AccountHolderName
{
get
{
return accountHolderName;
}
}
public double Balance
{
get
{
return balance;
}
}
public string UpdateAccountHolderName(string accountHoldername)
{
this.accountHolderName = accountHolderName;
return AccountHolderName;
}
}
You can test this with a console app like this:
class Program
{
static void Main(string[] args)
{
var ba = new BankAccount(10.00, "Bob", 123456);
ReadDetails(ba);
var newName = ba.UpdateAccountHolderName("Frank");
Console.WriteLine("New Name: " + newName);
ReadDetails(ba);
}
static void ReadDetails(BankAccount ba)
{
Console.WriteLine("Balance: " + ba.Balance + ", Name: " + ba.AccountHolderName + ", Number: " + ba.AccountNumber);
Console.ReadLine();
}
}
Results:
It's worth noting that monetary amounts are normally done using decimal, so you might want to reconsider using double for the balance.
UPDATE
Now updated to return the new name as part of the method

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.

Creating two C# class definitions with a driver to test classes, but not sure why so many errors?

I am new to C# and was asked to create two class definitions (customer and order) using partial code and with the suggested class names, methods, contructors and following an example. I am not sure why I am getting so many errors when I build/debug?
After this is finished, I need to create another program that builds onto this one. Our instructor also asked us not to use validation...
Some of my most common errors are:
expected: ; (in a place in my code where I believe there should not be a semi-colon and
Error "Expected class, delegate, enum, interface, or struct.
Here is my code:
public class clsOrder
{
//declare class variables
protected string cstrDescription;
protected int cintQuantity;
protected decimal cdecPrice;
protected decimal cdecExtendedPrice;
//shared variables
static decimal cdecTotalPrice;
static int cintTotalCount;
//declare constructors
public clsOrder();
}
public clsOrde r(string strDescription,
int intQuantity, decimal decPrice)
}
//declare property methods
{
this.Description = string strDescription;
this.Quantity = int intQuantity;
this.Price = decimal decPrice;
//declare read-only properties
public decimal ExtendedPrice
}
public string Description
{
get
{
return strDescription;
}
set
{
strDescription = value;
}
}
public int Quantity
{
get
{
return intQuantity;
}
set
{
intQuantity = value;
}
}
public decimal Price
{
get
{
return decPrice;
}
set
{
decPrice = value;
}
}
get
{
return cdecExtendedPrice;
}
}
//declare Shared (static) ReadOnly Properites
public static decimal TotalPrice
{
get
{
return cdecTotalPrice;
}
}
public static int TotalCount
{
get
{
return cintTotalCount;
}
}
//declare supporting methods
public void calcExtendedPrice()
{
cdecExtendedPrice = cintQuantity * cdecPrice;
}
public void accumulateTotals()
{
cdecTotalPrice += cdecExtendedPrice;
cintTotalCount += 1;
}
public static void resetTotals()
{
cdecTotalPrice = 0;
cintTotalCount = 0;
}
}//end of Class
}//end of namespace
And
public class clsCustomer
{
//declare class variables
private string cstrName;
private string cstrStreet;
private string cstrCity;
private string cstrState;
private string cstrZip;
//declare constructors
public class clsCustomer()
}
public clsCustomer(string strName,
string strStreet, string strCity,
string strState, string strZip)
}
//declare property methods
{
this.Name = cstrName;
this.Street = cstrStreet;
this.City = cstrCity;
this.State = cstrState;
this.Zip = cstrZip;
}
public string Name
{
get
{
return cstrName;
}
set
{
cstrName = value;
}
}
public string Street
{
get
{
return cstrStreet;
}
set
{
cstrStreet = value;
}
}
public string City
{
get
{
return cstrCity;
}
set
{
cstrCity = value;
}
}
public string State
{
get
{
return cstrState;
}
set
{
cstrState = value;
}
}
public string Zip
{
get
{
return cstrZip;
}
set
{
cstringZip = value;
}
}
Any help would be very much appreciated, thank you.

What is the simplest way to update a ConcurrentDictionary

I have created a ConcurrentDictionary but am unsure of how to update an element of it:
public class ModelClient : ICloneable
{
public Session session;
public List<string> keys = new List<string>();
public List<ModelOrder> orders = new List<ModelOrder>();
public ModelClient(SessionID sessionID)
{
session = Session.LookupSession(sessionID);
}
public object Clone() { return this.MemberwiseClone(); }
}
public class ModelOrder : ICloneable
{
private string Symbol;
private int Amount;
private double Price;
public ModelOrder(string Symbol, int Amount, double Price)
{
this.Symbol = Symbol;
this.Amount = Amount;
this.Price = Price;
}
public object Clone() { return this.MemberwiseClone(); }
}
public ConcurrentDictionary<SessionID, ModelClient> ModelClients = new ConcurrentDictionary<SessionID, ModelClient>();
Here is where I need to update (by adding a new element to orders), it appears that I should use TryUpdate, but it looks very cumbersome and hard to read.
Could someone show me a good way please.
public bool AddModelClientOrder(SessionID sessionID, string orderMessage)
{
string[] part = orderMessage.Split(' ');
//HOW DO I BEST DO THIS?
ModelClients[sessionID].orders.Add(new ModelOrder(part[0], int.Parse(part[1]), double.Parse(part[2])));
}

Derived Class to use property of Base class?

I have a class, with a public property "appController", as follows:
public class FAST
{
#region Props
public AppController.AppControllerClass appController = new AppController.AppControllerClass();
#endregion
#region Contructors
public FAST(AppController.AppControllerClass appcontroller)
{
this.appController = appcontroller;
}
#endregion
}
I have another few class, in which I would like to use the appController of FAST, the above class.They look like:
public class Forecast
{
#region Properties
private int _forecastnumber;
public int ForecastNumber
{
get { return _forecastnumber; }
set { _forecastnumber = value; }
}
private DateTime _startdate;
public DateTime StartDate
{
get { return _startdate; }
set { _startdate = value; }
}
private DateTime _enddate;
public DateTime EndDate
{
get { return _enddate; }
set { _enddate = value; }
}
private DateTime _deadline;
public DateTime Deadline
{
get { return _deadline; }
set { _deadline = value; }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private string _type;
public string Type
{
get { return _type; }
set { _type = value; }
}
private string _description;
public string Description
{
get { return _description; }
set { _description = value; }
}
private string _status;
public string Status
{
get { return _status; }
set { _status = value; }
}
#endregion
#region Constructors
public Forecast()
{
}
#endregion
#region Methods
public static void InsertForecast(Forecast forecast)
{
try
{
this.appController.Execute(appController.nDC.FASTData.InsertForecast(forecast.StartDate, forecast.EndDate, forecast.Deadline, forecast.Type, forecast.Name, forecast.Description, forecast.Status));
}
catch (Exception ex)
{
this.appController.LogError(ex);
}
}
#endregion
}
I want to be able to declare the FAST class once, passing in the AppController, then use my other classes freely, and they will use the appcontroller of the FAST class.
Can this be done at all? (inheritance?)
Thanks for any help.
It sounds like you simply want a static class for your FAST class. If you define the AppController variable as static, it will be accessible from anywhere.
I would say no to inheritance. Inheritance suggests an "is" relationship, e.g. "Forecast is a specialized version of the app controller." Aggregation, a specialized form of object composition, suggests a "has" relationship, e.g. "Forecast has an app controller."
http://en.wikipedia.org/wiki/Object_composition#Aggregation
You could add a setter method to set your FAST object as a property of Forecast:
public FAST appController { get; set; }
And then
var f = new FAST(new AppController.AppControllerClass());
var forecast = new Forecast();
var forecast2 = new Forecast();
forecast.appController = f;
forecast2.appController = f;

Categories

Resources