getter , setter c# - c#

i have got various custom datatypes in my web application to map some data from the database.
something like:
Person
Id
Name
Surname
and i need a List of persons in most of my application's pages
i was thinking to create a getter property that gets the list of persons from the database and store into cache in this way i do not have to call the database each time
something Like (pseudo code)
public List<Person> Persons
{
get { return if cache != null return List of Persons from cache else get from the database;}
}
Where shall i put this getter? in my Person class definition or into my base page( page from which all the others pages inherit)
Thanks

I think putting it in your base page would be better option.
Depending on your application architecture, putting process related code in your domain classes might be an issue. Some use it in DDD (domain-driven design) type applications though.
Better even, I usually try to hide those implementation details in a service class. You could have a PersonService class that would contain your above method and all person related operations. This way, any page requiring person information would simply call the PersonService; and you can concentrate your page code on GUI related code.

I don't think that you should put it in your Person class since it accesses the database and HttpContext.Current.Cache. Furthermore I think you should make it a method and not a property, to imply that this may be a "lengthy" operation. So, of the two options, I would put it on the base Page class.

Related

Where do you store "generic" class methods?

So let's say I have an Person entity:
PERSON
ID
FirstName
LastName
SSN
LastModifiedDate
After this table exists in the database, and is part of my .edmx file, I usually create a partial class for the entity to use to perform some object-specific work. For example, with the Person entity I might have an UpdateLastModifiedDate() method which would simply set the value for the LastModifiedDate field to the present date and time for the selected object.
My question, however has to do with more "generic" methods, that don't relate to any specific object. For example, let's say I wanted to create a GetPersonBySSN() method which would accept a SSN and return the Person object with that SSN (if it exists). Where would I store this method?
I couldn't store it in the partial class (could I?) because I would have to do something odd like this:
Person myPerson = db.Person.where(u => u.ID = 12345);
Person myPerson2 = myPerson.GetPersonBySSN(123456789);
It just doens't make sense to do it this way.
Also, I am reluctant to create a second static class to store these "generic" methods (like maybe a PersonGenericMethods class) because it feels like I should be able to do this with only the main class, Person.
Where would you store these "generic" methods?
Edit: I am using ASP.NET MVC and would like recommendations on how to best build using this.
Also, I am reluctant to create a second class to store these "generic" methods (like maybe a PersonGenericMethods class) because it feels like I should be able to do this with only the main class, Person.
How a bout a PersonRepository class? That class would be responsible for interacting with the underlying Person data store - getting, updating, deleting, etc.
What you seem to want is called the Active Record Pattern
where entity classes are responsible for creating, updating, and deleting themselves. While that's more common in other platforms like Ruby, in most .NET architectures the separation of the entity from the repository is more common.
The more separation you have (entities, repositories, business logic, UI logic, etc.) the more flexibility and re-usability you have. That comes, however, at the price of additional complexity.
The repository-pattern is perfect for this.
Do keep in mind that you are programming OO. It is strange to get the person from 'itself'.
A repository will get your data and return your desired result.
on a side-note:
Person myPerson = db.Person.where(u => u.ID = 12345);
Person myPerson2 = myPerson.GetPersonBySSN(123456789);
Is strange, first, you get the person where ID = ... and then as function on the person you want to make sure that ssn is the same number?
your repo would look like this:
public class PersonRepository
{
private readonly DBContext _myContext'
public PersonRepository(DBContext myContext)
{
_myContext = myContext; //<== Dependency INjection
}
public function Person GetBySSN(int ssn)
{
return _myContext.FirstOrDefault(p => p.ssn = ssn);
}
}
take a look at:
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
just gives a good basis.
and then for later improvements: can you look into Maybe and Results types, but if your new to this, forget it :)
enjoy!

Override or hide property in partial class

I have read around quite a bit now and think that the following is not doable, but I would like to have confirmation from experts if possible and possibly advice on a "best" workaround.
In all the auto-generated linq-to-sql classes I end up doubling up on all properties to carry out checks on the values as they are set, say, I have a Person class with a Name property on which I end up doing:
public partial class Person
{
public string Name
{
get { return this._Name; }
set
{
if (!string.IsNullOrEmpty(value))
{
value = value.trim();
this._Name = value.Substring(0, Math.Min(value.Length, 200));
}
else
throw new InvalidOperationException("Person name cannot be blank");
}
}
}
Simple check to ensure that when I persist to the database the name won't exceed the maximum length.
Which means I end up doubling up on nearly every single property from the auto-generated class and that makes a massive mess because they end up all being named something similar.
I tried adding a layer on top of the partial classes by making my own representation of the objects, but ran into problems when instantiating classes which depended one on the other... Say a person has a company, you instantiate person and its company which instantiates persons for the company, which reinstantiates companies etc...
Is there some "good" way to do what I am trying to do with the partial classes? If not, what are the alternatives that work best?
Maybe inheriting every single partial class and overriding the properties? Using the OnChange events to perform the checks?
The recommended approaches are laid out in ScottGu's blog post here: http://weblogs.asp.net/scottgu/archive/2007/07/11/linq-to-sql-part-4-updating-our-database.aspx
and again, here
http://geekswithblogs.net/AzamSharp/archive/2008/03/30/120875.aspx
Also, you might want to look into moving from L2S to Entity Framework, which provides more robust validation support.
It sounds to me like your trying to make linq to sql do something it was never intended to do. When I run into situations like this I start looking for a tool/library/orm etc that is better suited for what I am trying to accomplish

Complex domain model based on companies and not users

I have a few different types of companies that can access my web application e.g
Different types of Companies:
Client
Supplier
Agent
Each have their own table in the database, linked to the main table Company which stores all common data e.g. Address, Tel, Email, TypeOfCompany with a FK to the relevant table (Client etc.)...
What is the best way to handle this OO throughout my app?
I currently do something like:
public class CompanyDTO
{
public int Id {get;set;}
public string Name {get;set;}
public Address Address {get;set;}
public string Type {get;set;} //type of company
//etc...
}
then inherit from that class and add aditional properties e.g.
public class ClientDTO : CompanyDTO
{
public string Key {get;set;}
public Address Billing {get;set;}
}
However I am finding it problematic at times for example
Supplier user wants to access: AllCompanies, - show a list of all companies
Then the user from the Supplier Company wants to view a specific companies detail, now if it is a client I will need to show ClientDTO or SupplierDTO? In this instance I want to show that specific companies Full details
What would be the best way to handle this?
e.g. GetCompanyByID(int companyid); or GetClientByID(int clientid); What type of object should I return in both instances, presuming I want Client details in both instances...
Funny how databases don't understand OO practices like derivation, aggregation, and encapsulation. It is an unfortunate failing but still only a part of what is overall referred to as "database impedance mismatch".
What your attempting to do is common enough there are several solutions...
Firstly there is the choice of the data model stored. There are basically three possibilities.
Split the tables as you have done.
Declare all fields for all derived types in the same table.
Use a blob field (json/xml/whatever) to house the uncommon fields.
Secondly there is the issue you bring up, requesting the data from the database. Primarily this is centered around the request of a list of the 'common' base type and how to then access the uncommon fields that they don't share. Again there are several possibilities.
When listing the base type only those common fields are returned. Then subsequent queries are issued one-off to lazy load the other fields.
When listing the base type all other tables needed are also outer joined to the main table to ensure all fields are available to instantiate the object model fully.
When listing the base type, multiple result sets are returned, one for each 'sub type' table that may be needed for the results. The client then pieces the records together building up the object model until it is complete.
Not an exhaustive list, but a start. Personally I prefer to avoid data models like the one you describe for this reason. Essentially my preference is to have the data model define the union of all fields (model #2), and then use a business layer to determine what properties are exposed, validated, required, etc. I have also used model #3 above, using blob fields for multiple values, and it works well enough also depending upon need. The only downside to model #3 over #2 is that you will not be able to query or sort on those fields. Ultimately either approach still needs the business logic layer involved to know what data to expose.
Remember databases are stupid, treat them as such and you will get along well. (note: this advice does not work on people, just databases)
I want to access: AllCompanies, - show a list of all companies
When you want a list of companies, aren't you asking for the general details that instances of CompanyDTO describe? Maybe your data access (service, repository, etc) could look like:
public class CompanyRepository : ICompanyRepository
{
public IEnumerable<CompanyDTO> GetCompanies()
{
// get companies and map them to CompanyDTO objects as necessary
}
}
Then you asked (well, there is a question mark)
Then I want to view a specific companies detail, now if it is a client I will need to show ClientDTO or SupplierDTO?
I'm assuming this would be a separate view, or at least broken down into a separate partial views. But, you could use Display Templates to describe your child types of companies since you've describes an inheritance above.
I will pretend you showed us your controller and it looks like this:
public class CompanyController : Controller
{
public ActionResult Details(int id)
{
CompanyRepository repo = new CompanyRepository();
return View(repo.GetCompanyById(id));
}
}
Then, add a strongly-typed view named Details, that inherits a CompanyDTO object, and add a call to Html.DisplayForModel():
<%--some scaffolded code ommitted for brevity--%>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<%= Html.DisplayForModel() %>
</asp:Content>
Then, here's where display templates come in. Add a folder:
~/Views/Company/DisplayTemplates
Then add to that folder 3 strongly-typed, partial views--one for each child type. Visual Studio will help you with this:
Right-click the DisplayTemplates folder --> Add View...
Name it "ClientDTO" (this is important)
tick "Create a partial view"
tick "Create a strongly-typed view"
Select the ClientDTO class
Select Details for view content (this will give you some auto generated markup)
Click Add
Repeat this process for other child types and the correct template will be rendered based on the child type of the model passed to your Details view.

What is the preferred model configuration for CRUD?

I am attempting to perform crud operations within a simple content management website. In attempting to create my CRUD views for the entering of a piece of content, there are several drop-downs that need to be populated, and in the case of an edit operation they need to have specific values pre-selected. I have been reading a textbook on it and absorbing as much as I can through articles on the web, but I'm having trouble in determining where the best place is for the information belonging to these drop-downs. I could easily create model classes to identify them, and then I would have an option of either getting the data to fill them one at a time or have this information populated as properties in my content model class so that the value of the class is selected, but an IEnumerable property would be available to bind to directly.
Either way seems to work with using templates to create the drop-downs, but I'm trying to eliminate some of the "Select N+1" issues of retrieving these things individually, but I also don't want to pack my model full of too much junk that really doesn't belong there as considered against the MVC architecture.
So the basic question is: Does supporting information like drop-downs, filters, etc belong as sub-classes in the primary model class or should these be retrieved individually and presented as separate items by themselves? Or is there some other aspect to the architecture that should be used and I'm just missing the boat completely?
Articles, links, redirects are all welcomed. I have Googled this, and what I have found has either not answered this question or the answer is hiding within the mass of results.
example: Books and Authors entities
when creating a new book in a view, you need a select control that has its options populated as all the available authors.
the Book model should be clean and contain only the relevant fields e.g. Title, Author
the controller should have an IAuthorRepository _authorRepository; field that could have been set by a DependencyResolver or manually in the controllers constructor. IAuthorRepository would have a method such as IEnumerable GetAvailableAuthors();
the [HttpGet] Create() action could return an empty Book model directly and then stuff the _authorRepository into the dynamic ViewBag. ViewBag.AuthorRepository = _authorRepository;
The view would then pass the ViewBag.AuthorRepository to a partial view or a custom editor. Your model is kept clean in this scenario.
Some people don't like any use of ViewBag.Xxx (or ViewData["Xxx"]) because it's less than perfect MVC. I've seen examples that would Create a new type like BookViewModel. BookViewModel would then contain Book and IAuthorRepository in itself. the [HttpGet] Create() action would then return a BookViewModel object and the view would render its Author Select partial view by passing it the model.AuthorRepository instead of the ViewBag.AuthorRepository. This sort of starts to look more like MVVM here rather than MVC. Your instinct to keep any such collections or repositories out of the actual model (Book) is right. A clean model is very important and will give you the most flexibility in any pattern.
Not sure if this is the thing you are after but I use my own class library called Web.Shared which holds all my helper methods. I have a SelectListHelper class which I use to populate all my dropdownlists. That way my code is seperated from the main domain model and can be reused through this and any other MVC app which is part of my solution.
// Return days of the month for a dropdownlist
public static class SelectListHelper
{
public static SelectList DayList()
{
return NumberList(1, 31);
}
}
// Use in view
#Html.DropDownListFor(m => m.Day, SelectListHelper.DayList())
// Another one for selecting genders
public static SelectList GenderList(string selectedValue = null)
{
IList<KeyValuePair<string, string>> genders = new List<KeyValuePair<string, string>>();
genders.Insert(0, new KeyValuePair<string, string>("F", "Female"));
genders.Insert(0, new KeyValuePair<string, string>("M", "Male"));
genders.Insert(0, new KeyValuePair<string, string>("", "Choose Gender"));
return new SelectList(genders, "Key", "Value", selectedValue);
}
// Use in my edit view
#Html.DropDownListFor(m => m.Gender, SelectListHelper.GenderList())
Failing this take a look at MVC Scaffolding for creating data bound CRUD Views.
I agree with Tion's answer but my response can't fit in a comment.
First, the simple solution if you're using NHibernate: you can setup batching on has-many collections to load many entities in one query (instead of N!). We use a batch size of 100 with very noticeable performance gains. This won't help if you're just loading everything from a single table.
Now the trickier, but still very worthwhile solution.
If you have fairly static content that gets queried often (drop down lists, account name lookups, etc) you should really think about caching it in memory. If you're using IOC it's very easy to swap in a CachingRepository implementation for IRepsoitory<>. At my company we borrowed FubuCache from FubuMVC, but I think it's just a dictionary behind the scenes. If you have a server farm or multiple servers accessing the same data, you can use Memcached to share data.
The important thing about caching is knowing when to clear it. (ie, reload content from the database.) For us that means
1) every 5 minutes no matter what (other applications interact with the db so we need to pick up their changes.
2) any time an entity is inserted or updated we clear all the relevant caches.
Since most of our applications are reporting over large datasets with many joins we cache nearly everything. As long as your server has enough RAM you'll be fine.
ps http://axisofeval.blogspot.com/2010/11/numbers-everybody-should-know.html

C# classes and methods

I find it difficult to determine the responsiblity of classes: do i have to put this method in this class or should I put this method in another class? For example, imagine a simple User class with an id, forname, lastname and password. Now you have an userId and you want the forname and lastname, so you create a method like: public User GetUserById(int id){}. Next you want to show list of all the users, so you create another method: public List GetAllUsers(){}. And offcourse you want to update, delete and save a user. This gives us 5 methods:
public bool SaveUser(User user);
public bool UpdateUser(User user);
public bool DeleteUser(User user);
public User GetUserById(int id);
public List<User> GetAllUsers();
So my question is: do you put all these methods in the User class? Or do you create another data class (UserData class) which may connect to the database and contain all these methods?
What you are describing here is basically a choice between the Active Record Pattern or the Repository Pattern. I'd advise you to read up on those patterns and choose whichever one fits your application / experience / toolset.
I would not put those specific methods into the 'User' class.
There are 2 common approaches for this 'problem':
You put those method in the User
class, and then this means you 're
using the Active Record pattern
You put those methods in a
separate class (UserRepository) for
instance, and then you're using the
Repository pattern.
I prefer the repository-approach, since that keeps my 'User' class clean, and doesn't clutter it with data access code.
Barring additional complexity specific to a group of users (or really elaborate database access mechanics) I might make those methods static on the User class.
Those methods sound more like a UserManager (or something like that) to me. The user class should correspond to and represent only a single user, not many.
If we look at Enterprise Application design patterns, then the methods for fetching Users i.e. GetUserByID and GetAllUsers would be in separate class - you can name it UserData or UserDAO (DAO - Data Access Object).
Infact you should design an interface for UserDAO with appropriate methods for handling User Objects - such as CreateUser, UpdateUser, DeleterUser, GetUserXXX and so on.
There should be an implementation of UserDAO as per the data source, for example if your users are stored in database then you can implement the logic of accessing database in the implementation of UserDAO.
Following are the advantages of keeping the access methods in separate class:
1) User object should be plain object with just getter setter methods, this would facilitate passing object across tiers - from data access tier, to business tier to web tier. This would also help keep User Object serializable
2) The data access logic is loosely coupled from the User object - that means if the datasource changes, then you need not change the User object itself. This also assists in Test Driven Development where you might need to have mock objects during testing phase
3) If User object is complex object with relations with other objects such as Address or Department or Role etc. then the complexity of relationships will be encapsulated in UserDAO rather than leaking in the User Object.
4) Porting to frameworks like NHibernate or Spring.NET or .NET LINQ would become easier if the patterns are followed
Lets us see you scenario as this.
There are 'N' number of people working in assembly division of you company.
It is okay to go to a person and ask about his information BUT you cant expect him to tell you details of all persons working in assembly division. Reason why shud he remember all the details and if you do expect then his effeciency will go down(work on assembly and also remember details of others).
So ..... perhaps we can appoint a manager who can do this ppl maanagement activities
(get details, add new person, edit ,delete etc etc )
Therefore you have two entities
1) User/Person working in your assembly deivision
2) a Manager
Thus two classes. Hopes this will help you.
Thanks
If I understand your question correctly the User class deals with a single user. Hence the user class does not have a clue about how many users there are or anything about them. The structure holding this information is somewhere else and the methods you mention seem to belong to that structure / class.
With all else being equal either way is fine. Which to choose, though, usually depends on the overall architecture of the application or class library in which you find the User class. If the data access code seems tangled with the User object code, then it might make more sense to split it into two classes as you've considered. If the CRUD methods are one-line delegations to a DAL with maybe application-specific logic, then leaving them in the User class should be okay.
The complexity is more or less the same in both cases—it's a trade-off between a low-maintenace assembly with few high-maintenance classes or a high-maintenance assembly with a larger number of low-maintenance classes.
I'm also assuming that the CRUD methods should be static.
Do what's easiest to get the code written right now but consider possible refactorings in the future should you find that it'll be better that way.

Categories

Resources