C# ConcurrentDictonary Setting values in collection other then the key - c#-4.0

Please look through my code before closing it this time.
The code below works but seems very hacked, I am looking for suggestions on to achieve the same thing with cleaner code or is this as good as it gets.
The code calling the Add and Remove will be from different threads that could possible access the code at the same time, so it must remain thread-safe.
using System;
using System.Collections.Concurrent;
namespace Server
{
public class Company
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public ConcurrentDictionary<string, Employee> Employees = new ConcurrentDictionary<string, Employee>();
}
public class Employee
{
public string First { get; set; }
public string Last { get; set; }
public string Ext { get; set; }
}
public class Clients
{
public ConcurrentDictionary<string, Company> CompaniesDict = new ConcurrentDictionary<string, Company>();
public bool Add_Company(string ID, string Name, string Address, string Phone) //This function works
{
Company MyCompany = new Company();
Employee MyEmployees = new Employee();
MyCompany.Name = Name;
MyCompany.Address = Address;
MyCompany.Phone = Phone;
MyCompany.Employees = MyEmployees;
return CompaniesDict.TryAdd(ID, MyCompany);
}
public bool Remove_Company(string ID) //This function works
{
return CompaniesDict.TryRemove(ID, Company tCompany);
}
//This is were I need the help this seems so hacked. Im not trying to update the key, but the value intstead
public bool Set_CompanyName(string ID, string Name)
{
CompaniesDict.TryGetValue(ID, out Company oCompany);
Company nCompany;
nCompany = oCompany;
nCompany.Name = Name;
return CompaniesDict.TryUpdate(ID, nCompany, oCompany);
}
public string Get_CompanyName(string ID)
{
CompaniesDict.TryGetValue(ID, out Company tCompany);
return tCompany.Name;
}
}
}
Please don't just close this and link me to some useless code you call a duplicate. Sorry to be so blunt but this has recently happened to me by a fellow coder on this site. If you have questions that I can answer so that you can full help me please ask them.
Thanks for you help in advance.

There is a much easier approach, as you are updating a field on an object.
Please note that I don't have C# installed on my current PC, so can't validate this.
Note that I declare the out parameter, but don't construct a new one that would be destroyed immediately and I modify the object itself.
i.e.
Company company;
not
Company company=new Company();
This will still not be deterministic if multiple threads call SetCompanyName(), as the new name is updated on the live object and there could be a potential race condition. However the Add and Remove will be, even if Remove removes the company instance just before its name is updated.
public bool Set_CompanyName(string ID, string Name)
{
Company company;
var retval= CompaniesDict.TryGetValue(ID, out company)
if (retval) {
company.Name=Name; // Update your company object directly
}
//else Do something such as throw an exception if it's not found
return retval;
}

Related

DDD: Administration and encapsulation

What are your methods to deal with the communication of an admin panel with a domain in the case of changing values of properties of an entity without breaking the encapsulation?
public class Book : Entity {
public Book(string title, string author, string description, decimal price, short publicationYear) {
Title = title;
Author = author;
Description = description;
Price = price;
PublicationYear = publicationYear;
}
public string Title { get; private set; }
public string Author { get; private set; }
public string Description { get; private set; }
public decimal Price { get; private set; }
public short PublicationYear { get; private set; }
}
The only way to not break encapsulation is to include some parts of the presentation logic into the object itself. Not the details, mind you, but the parts which are highly coupled to this object.
I would do something like this (pseudo-code):
public class Book {
public Book(...) {
...
}
public InputComponent<Book> createAdminView() {
return new FormGroup<Book>(
new TextInput(title),
new TextInput(author),
...);
}
}
This way there is no need to publish any of the internal data fields of the object, nobody needs to know how to book looks like, and all changes related to the object will be localized.
In fact, I've been doing this for a couple for years now, and this design results in much easier to maintain code. Have a look at my presentation about Object-Oriented Domain-Driven Design to find out more: https://speakerdeck.com/robertbraeutigam/object-oriented-domain-driven-design

DDD Service Method Granularity

So, I'm building a system for managing contacts. My contact domain model has quite a few string properties, as well as booleans. In the spirit of keeping behavior inside of the domain models, I've gone down the path of creating "update methods." I'm starting to feel like it's getting a bit burdensome. In the past, CRUD apps would just have a single update method and it would set all of the properties in one shot.
Am I on the right path? I'm concerned about having 10 - 15 update methods on my domain service and domain entities.
FYI, the example given is a bit contrived, so imagine a model with lots of string and boolean properties.
// Application Layer Stuff
public class UpdateContactCommand
{
public UpdateNamePredicate UpdateName { get; set; }
public UpdatePhonePredicate UpdatePhone { get; set; }
public int ContactId { get; set; }
}
public class UpdateNamePredicate
{
public string NewFirstName { get; set; }
public string NewLastName { get; set; }
}
public class UpdatePhonePredicate
{
public string NewPHone { get; set; }
}
public class UpdateContactResponse
{
public bool Success { get; set; }
public string Message { get; set; }
}
public interface IWcfService
{
UpdateContactResponse UpdateContact(UpdateContactCommand updateContactCommand);
}
public class WcfService : IWcfService
{
private readonly IContactService _contactService;
public WcfService(IContactService contactService)
{
_contactService = contactService;
}
public UpdateContactResponse UpdateContact(UpdateContactCommand updateContactCommand)
{
if (updateContactCommand.UpdateName != null)
{
_contactService.UpdateName(updateContactCommand.ContactId, updateContactCommand.UpdateName.NewFirstName,
updateContactCommand.UpdateName.NewLastName);
}
if (updateContactCommand.UpdatePhone != null)
{
_contactService.UpdatePhone(updateContactCommand.ContactId, updateContactCommand.UpdatePhone.NewPHone);
}
return new UpdateContactResponse();
}
}
// Domain Layer
public interface IContactService
{
// There are lots more of these
void UpdateName(int contactId, string newFirstName, string newLastName);
void UpdatePhone(int contactId, string newPhone);
}
public class ContactService : IContactService
{
private readonly IContactRepository _contactRepository;
public ContactService(IContactRepository contactRepository)
{
_contactRepository = contactRepository;
}
public void UpdateName(int contactId, string newFirstName, string newLastName)
{
var contact = _contactRepository.GetById(contactId);
contact.SetName(newFirstName, newLastName);
_contactRepository.Commit();
}
public void UpdatePhone(int contactId, string newPhone)
{
var contact = _contactRepository.GetById(contactId);
contact.SetPhone(newPhone);
_contactRepository.Commit();
}
}
public interface IContact
{
int Id { get; set; }
// There are lots more of these
void SetName(string newFirstName, string newLastName);
void SetPhone(string newPhone);
}
public class Contact : IContact
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public void SetName(string newFirstName, string newLastName)
{
FirstName = newFirstName;
LastName = newLastName;
}
public void SetPhone(string newPhone)
{
Phone = newPhone;
}
}
public interface IContactRepository
{
IContact GetById(int id);
void Commit();
}
public class ContactRepository : IContactRepository
{
public IContact GetById(int id)
{
// Not important
throw new NotImplementedException();
}
public void Commit()
{
// Not important
throw new NotImplementedException();
}
}
First of all, not all applications lend themselves well to a DDD approach. If you say your application could pretty much have been implemented in a CRUDish way before, chances are it's still CRUD now. Don't try to apply DDD on any app because it's the shiny new thing.
That being said, you don't just write "update methods" for the fun of it. They have to reflect the domain tasks your user wants to perform. Why does the user want to update a Contact ? Has the contact moved or just changed phone number ? Changed marital status and name ? Has the point of contact in a company been taken over by another employee ?
Usually, you won't have tons of update methods for a given entity. There's always a way to group changes in operations that are meaningful for the domain. Good ways to force yourself to do it are :
Think about the maximum number of form fields you can reasonably display to the user. Couldn't you split that complex UI into smaller, more meaningful screens ? From there you have to start reasoning (preferably with the help of a domain expert) about the tasks these should reflect.
Make your entity fields immutable from the outside. Thus you'll have to think harder about their true nature -- what should be in the constructor ? what should some other manipulation methods be ?

JSON.NET Object Deserialisation with class

I am using these classes:
public class MasteryPages
{
internal MasteryPages() { }
[JsonProperty("pages")]
public List<MasteryPage> Pages { get; set; }
[JsonProperty("summonerId")]
public long SummonerId { get; set; }
}
[Serializable]
public class MasteryPage
{
internal MasteryPage() { }
[JsonProperty("current")]
public bool Current { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("talents")]
public List<Talent> Talents { get; set; }
}
[Serializable]
public class Talent
{
internal Talent() { }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("rank")]
public int Rank { get; set; }
}
This is the code I'm using to deserialise the object
//MASTERIES
var jsonMasteries = requester.CreateRequest(string.Format(RootUrl, Region) + string.Format(MasteriesUrl, summonerId));
var objAllMasteryPages = JsonConvert.DeserializeObject<MasteryPages>(jsonMasteries);
The jsonMasteries object is correctly serialized and gives me this:
http://pastebin.com/3dkdDHdx (Rather large, to view easily: go to http://www.jsoneditoronline.org/ and paste it)
The second line is giving me troubles however. Normally my object should be filled with the data. It unfortunately isn't and I have no idea what's wrong.
Anyone could help me out?
Your problem is in this part of serialized JSON: "42177333": { ... }
As I understand - this is some kind of ID and it's dynamic.
Possible solutions are:
One of possible resolutions is here: C# deserialize dynamic JSON
Cut this part of dynamic JSON.
Try to modify the serialization stuff to avoid this dynamic ID.
Thanks to sleepwalker I saw what was wrong. (Dynamic Id (number), first line)
Now, the James Newtonking JSON library has a solution for dynamic id's like this.
I edited my code to this:
var jsonMasteries = requester.CreateRequest(string.Format(RootUrl, Region) + string.Format(MasteriesUrl, summonerId));
var objAllMasteriePages = JsonConvert.DeserializeObject<Dictionary<long, MasteryPages>>(jsonMasteries).Values.FirstOrDefault().Pages;
(First line stays the same, the magic is in the second line)
Now, i use a dictionary with the key being my given Id, and my custom class.
This works wonders

REST Routing in ServiceStack

I just start to learn REST and ServiceStack and there's something about Route that I just can't quite understand. For example if we take the very basic HelloWorld example from GitHub tutorial and re-write it to return collection of User objects. Here is example:
public User
{
public string Name;
public string Address;
public int Age;
}
// Hello - request object without [Route] attribute
public class Hello
{
public string Name { get; set; }
}
public class HelloResponse
{
public IEnumerable<User> Result {get;set;}
}
public class HelloService : Service
{
public object Any(Hello request)
{
return new HelloResponse { // Collection of User object };
}
}
now everything working right and no problems here. But now I want to add another routing url like: /Hello/{name}/Address
Actually this call (GET) to this url will return a single User selected by Age parameter. How I can do this ? Should I add another Service ? And if the url will be:
/Hello/{name}/{age}/Address
It seems I don't understand something.....
See this earlier answer for details about Routing in ServiceStack. The Smart Routing section in ServiceStack's New API explains further options and different precedence.
There are a few problems with your example. First ServiceStack text serializers only support public properties so you need to change your User Model to use public properties instead of fields, e.g:
public User
{
public string Name { get; set; }
public string Address { get; set; }
public int Age { get; set; }
}
Next, Interfaces on DTOs are a bad idea as there's no good reason for it. They're still supported but you can end up with undesirable results. Use a concrete collection like a List<T> which provides more utility, e.g:
public class HelloResponse
{
public List<User> Results { get; set; }
}
Also the routes should match the property names on your DTO exactly, they are case-insensitive when matching against the Request Path, but they need to map to an exact property name, e.g:
/Hello/{Name}/{Age}/Address

SubSonic, SimpleRepository and entity interfaces

Firstly, I want to apologize for my English, not my strongest side.
To the question. In my current project, I have interfaces to my entities so I can use Subsonic attributes at my head entites and I want to be able to seamlessly switch O/R mapper in the future.
Anyway, I get an error when I try to use my interfaces and SimpleRepositorys classes like Single<>, All<> and so on.
I know why I get the error message but I need help to find a way to get around it.
Error message:
System.InvalidCastException: Unable to cast object of type 'SubSonic.DomainObjects.User' to type 'Core.DomainObjects.IUser'.
Code:
public IUser FindById(int id) {
var user = _repository.Single<User>(x => x.Id == id);
return (IUser)user;
}
As you can see I have tried to make User to IUser order to work when I want to add data, but without success. What can I do to make this work?
Thank you,
Timmie
I don't think subsonic is the problem in this situation. This code will work:
namespace Core.Objects
{
public interface ICustomer
{
int CustomerID { get; set; }
string Name { get; set; }
}
}
Code for the actual class:
namespace Business.Entities
{
public class Customer: Core.Objects.ICustomer
{
public int CustomerID { get; set; }
[SubSonicStringLength(50)]
public string Name { get; set; }
}
}
And finally, the function to get the customer:
private static ICustomer CustomerByID(int id)
{
var repos = new SimpleRepository("Test", SimpleRepositoryOptions.None);
var customer = repos.Single<Customer>(c => c.CustomerID == id);
return (ICustomer) customer;
}

Resources