What is the simplest way to update a ConcurrentDictionary - c#

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])));
}

Related

How to serialize a Dictionary<object, guid>?

I'm currently building an application where I have some tasks that are sharing a Dictionary<Object, Guid>.
To avoid conflicts, the actual Dictionaries are contained within a DictionaryHandler-class with three methods:
class DictionaryHandler
{
private object lockProcesses = new object();
private Dictionary<Process, Guid> processes = new Dictionary<Process, Guid>();
public Dictionary<Process, Guid> GetProcesses()
{
lock (lockProcesses)
{
// TODO
}
}
public void AddToProcesses(Process process, Guid guid)
{
lock (lockProcesses)
{
processes.Add(process, guid);
}
}
public void RemoveFromProcesses(Process process)
{
lock (lockProcesses)
{
processes.Remove(process);
}
}
}
For context, this is the Process-class:
public class Process
{
public string Name { get; }
public bool Enabled { get; }
public TimeSpan RuntimeWindowStart { get; }
public TimeSpan RuntimeWindowEnd { get; }
public TimeSpan Cooldown { get; }
public int Priority { get; }
public string Username { get; }
public string ExceptionDate { get; }
public string ExceptionDay { get; }
public string AllowedWorkdays { get; }
public string SpecificResource { get; }
public string Assigned { get; set; }
public DateTime? Timestamp { get; set; }
public Process(string name, bool enabled, TimeSpan runtimeWindowStart, TimeSpan runtimeWindowEnd, TimeSpan cooldown, int priority, string username, string exceptionDate, string exceptionDay, string allowedWorkdays, string specificResource, string assigned, DateTime? timestamp)
{
Name = name;
Enabled = enabled;
RuntimeWindowStart = runtimeWindowStart;
RuntimeWindowEnd = runtimeWindowEnd;
Cooldown = cooldown;
Priority = priority;
Username = username;
ExceptionDate = exceptionDate;
ExceptionDay = exceptionDay;
AllowedWorkdays = allowedWorkdays;
SpecificResource = specificResource;
Assigned = assigned;
Timestamp = timestamp;
}
}
My main issue is that I want to find a way to return a copy of the Dictionary through the GetProcesses()-method, without returning a reference to the "actual" dictionary.
As far as I can see, the optimal way to do this is to Serialize and Deserialize the Dictionary and return that. But I'm having a hard time doing this, as I'm unable to find an example that matches my case.
I've read this and this and tried to combine the two - unfortunately without luck.
My main issue is that I want to find a way to return a copy of the Dictionary through the GetProcesses()-method, without returning a reference to the "actual" dictionary.
If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary:
new Dictionary<Process, Guid>(processes);
If you do need to clone the values, you can use something like:
public static Dictionary<Process, Guid> DeepClone<TKey, TValue>(Dictionary<Process, Guid> source)
{
var ret = new Dictionary<Process, Guid>(source.Count, source.Comparer);
foreach (var entry in source)
{
ret.Add(entry.Key, entry.Value);
}
return ret;
}
If you do need create a copy of Process class instance while copying dictionary, you may use:
public class Process
{
// some properties here
public Process ShallowCopy()
{
return (Process) this.MemberwiseClone();
}
}
public static Dictionary<Process, Guid> DeepClone<TKey, TValue>(Dictionary<Process, Guid> source)
{
var ret = new Dictionary<Process, Guid>(source.Count, source.Comparer);
foreach (var entry in source)
{
ret.Add(entry.Key.ShallowCopy(), entry.Value);
}
return ret;
}
Use String instead of Guid.
Guid is structure type. Therefore serialize and deserialize methods might not work correctly.

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

Using Enumeration Class

I'm new to C# and I'm relatively new to abstract classes and inheritance and I'm having troubles understanding how to use them. I have this abstract enumeration class:
public abstract class Enumeration : IComparable
{
public uint Id { get; private set; }
public string Name { get; private set; }
public uint MaxTemperature { get; private set; }
public double Density { get; private set; }
protected Enumeration()
{
}
protected Enumeration(uint id, string name, uint maxTemprature, double density)
{
Id = id;
Name = name;
MaxTemperature = maxTemprature;
Density = density;
}
public static IEnumerable<T> GetAll<T>() where T : Enumeration,
new()
{
var type = typeof(T);
var fields = type.GetTypeInfo().GetFields(BindingFlags.Public
| BindingFlags.Static | BindingFlags.DeclaredOnly);
foreach (var info in fields)
{
var instance = new T();
var locatedValue = info.GetValue(instance) as T;
if (locatedValue != null)
{
yield return locatedValue;
}
}
}
public override bool Equals(object obj)
{
var otherValue = obj as Enumeration;
if (otherValue == null)
{
return false;
}
var typeMatches = GetType().Equals(obj.GetType());
var valueMatches = Id.Equals(otherValue.Id);
return typeMatches && valueMatches;
}
public int CompareTo(object other)
{
return Id.CompareTo(((Enumeration)other).Id);
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
This class is inherited by my material class:
class Material : Enumeration
{
public static readonly Material FreeSpace =
new Material(0, "Free Space", 0, 0);
public static readonly Material CarbonSteel =
new Material(1, "Carbon Steel", 2500, 0.284);
private Material()
{
}
private Material(uint id, string name, uint maxTemperature,
double density) : base(id, name, maxTemperature, density)
{
}
private static IEnumerable<Material> List()
{
return new[] { FreeSpace, CarbonSteel };
}
}
Now I want to use these materials in my part class:
class Part
{
private Material partMaterial;
public Part() { }
public Material PartMaterial
{
set
{
partMaterial = value;
}
}
}
This is where I'm stuck, how do I set a variable as one of the enumerated static objects so I can get the properties from those?
You can use SelectedItem instead of SelectedIndex
part.PartMaterial = (Material) MaterialCombo.SelectedItem;
So, I wish I would have left the question the way it was, because in the end it was the correct way to ask the question. But after the snide comments and down grading I changed it to what I thought was better. The way the original question should have been answered was:
Since you are enumerating the materials class, you need a method to expose the Enumerated values of the objects. The
IEnumerable<Material> List() method should be made public to accomplish this.
You can then use MaterialCombo.DataSource = Material.List() to populate the combobox with the material objects and MaterialCombo.DisplayMember = "Name"; to display the names of those objects in the combobox.
Finally, use #Oxald's answer to pass the material to your part class.
Thank you #Mark Benningfield for pointing me in the direction to search for "Using an enum to populate a combobox" which was helpful.
And Oxald for suggesting to use .SelectedItem instead of .SelectedIndex.

Can't serialize custom class

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.

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.

Categories

Resources