Storing Methods in Entity Framework Database - c#

Is there a simple way to store methods in an EF table, akin to inheritance?
For example, I have a table representing apps on a portal page (kind of like your basic iphone or android home screen). I'd like to display a number by each app showing how many notifications the app has. However, the method to get the number of notifications varies greatly depending on the app.
My current solution is to just have a class containing all the methods I need, and then switch based on the app name. Is there a better way?

Assuming that your method to obtain the notifications is parameterless, you could store the method name in a column in that table and invoke it via reflection. For this example we'll call the column/property NotificationMethodName.
//this would go in your entity class
public int GetNotificationCount()
{
MethodInfo mi = typeof(HelperClass).GetMethod(this.NotificationMethodName);
return (int)mi.Invoke(this, null);
}
public class HelperClass
{
//your class that currently has all the methods to get notification count
}

Related

Best pattern for labels on website based on client profile

I have a requirement to make our current web application configurable based on client profile. So basically, allowing the application to scale and customize itself based on who the customer is. My current requirement to start off with will be simple, which is to make text within the web application configurable. So ATM, there will be 2 possible profiles, and based on which profile you select (either through AppSetting or database), all labels need to render accordingly. I can think of many ways of doing this. One thing I don't want to do is storing the label values in a database table because ATM there is no requirement to modify the labels through an interface, so I was thinking perhaps Resource files?
Also, my next requirement will be to all features within the website to be turned on/off based on profile, so I Need to keep this into consideration. Sometimes a feature will share 90% of the logic, so it wouldnt be feasible to duplicate to the feature and make the 10% changes for that profile and then have 2 copies of the same feature with minimum differences. So I'm looking for a solution for this as well. Perhaps an overall design that would cover both requirements?
Any advice will be highly appreciated.
Thanks
According to my understanding you need to update labels in the website and provide some features based on the profile selected.
So to do this , I would like to do this:
First implement MVC pattern, where our website will be in View , Model will be the Profile class and controller will host all the business logic.
If we don't want to use Database, we can serialize the object of Profile class and store (for ref
), in that we can have a File object which is a config file, where we can store the names of the features available to that profile.
At run time read all the features available for that profile and hence populate the view(website). This can be done by using either Inversion of Control Pattern. Like this:
public interface IFeatures{...}
public class Feature1 implements IFeatures{...}
public class Feature2 implements IFeatures{...}
public class Profile{
private String name;
private String pwd;
private File configFile;
...
}
public class Controller{
public List<?> getFeauturesForProfile(Profile p){
List<IFeatures> features;
List<String>feautures = scanConfigFileForFeatures(p.getConfigFile());
for(String feature : features)
features = Class.forName(feature).newInstance();
return features
}
}
Since I'm familiar with only java , I have written the syntax-es in java .

Questions on implementing Command Pattern in C# MVC

I'm hoping this is straight forward. I'm trying to implement the Command Pattern in my MVC application I'm making. The only issue I'm seeing is that the number of Command objects is really high.
I have 11 tables each with around 20 fields that need to be updated.
My question is do I need to have a different object for each field?
This is a healthcare application, so let me give an example.
I have a table called KeyHospital, this table stores Hospital information and only Hospital information for our Hospital Clients. I've used Linq to SQL for my connection to the database. The KeyHospital table is probably the largest as far as fields go. What I've done is create a new object per field.
public class ChangeHospitalDEA : ICommand
{
public ChangeHospitalDEA(int id, string newDEA)
{
var Thishospital = (from Hospital in _context.Keyhospitals
where Hospital.ID == id
select Hospital).Single();
Thishospital.DEAnum = newDEA;
}
}
I have ICommand as an abstract class.
public abstract class ICommand
{
public AllkeysDataContext _context = new AllkeysDataContext();
public void Execute()
{
_context.SubmitChanges();
}
}
Am I doing this correct? I just feel like I'm writing lots of code for this and it's one of my first times using the Command Pattern.
Considerably too granular. Instead, you should define commands for actions such as inserting a new entity, (graph of one or more related objects) updating an entity, etc.
A command would be used whenever you want to perform an action. In some cases changing a single field may constitute an action, such as returning additional data, or providing suggestions. Such as an AJAX call to validate an entered address. Also, ICommand is a poor name choice for a base abstract class. ICommand is a common interface for command architectures. (the "I" prefix is conventionally reserved for interface names.) I deal predominantly with MVVM but I would suspect that MVC has a common command interface already.
This is might not be what you want to hear but I would restructure your user interface to be Tasks based UI and construct your UI into common Tasks for example Change Drug Enforcement Administration number and these tasks can be refined over time.
If you have existing analytics you will notice that certain field will be only changed together and these could be logically grouped into common tasks
I also feel that is it is a bad practice to hide database calls within constructors and would move that linq statement to the Execute method and have the ctor only initialise public properties or private fields and have them field being used within the execute method.
Major reason for moving the query into the execute method is to reduce the time the chances of any Optimistic concurrency errors.
Also I also feel that calling the Base class ICommand is not a good practice and may lead to confusion in the future and would recommend you calling it CommandBase or changing it to an interface once again.

Single class with two databases

I have a two part application. One part is a web application (C# 4.0) which runs on a hosted machine with a hosted MSSQL database. That's nice and standard. The other part is a Windows Application that runs locally on our network and accesses both our main database (Advantage) and the web database. The website has no way to access the Advantage database.
Currently this setup works just fine (provided the network is working), but we're now in the process of rebuilding the website and upgrading it from a Web Forms /.NET 2.0 / VB site to a MVC3 / .NET 4.0 / C# site. As part of the rebuild, we're adding a number of new tables where the internal database has all the data, and the web database has a subset thereof.
In the internal application, tables in the database are represented by classes which use reflection and attribute flags to populate themselves. For example:
[AdvantageTable("warranty")]
public class Warranty : AdvantageTable
{
[Advantage("id", IsKey = true)]
public int programID;
[Advantage("w_cost")]
public decimal cost;
[Advantage("w_price")]
public decimal price;
public Warranty(int id)
{
this.programID = id;
Initialize();
}
}
The AdvantageTable class's Initialize() method uses reflection to build a query based on all the keys and their values, and then populates each field based on the database column specified. Updates work similarly - We call AdvantageTable.Update() on whichever object, and it handles all the database writes. It works quite well, hides all the standard CRUD, and lets us rapidly create new classes when we add a new table. We'd rather not change it, but I'm not going to entirely rule it out if there's a solution that would require it.
The web database needs to have this table, but doesn't have a need for the cost data. I could create a separate class that's backed by the web database (via stored procedures, reflection, LINQ-TO-SQL, ADO data objects, etc), but there may be other functionality in the Warranty object which I want to behave the same way regardless of whether it's called from the website or the internal app, without the need to maintain two sets of code. For example, we might change the logic of how we decide which warranty applies to a product - I want to need to create and test that in only one place, not two.
So my question is: Can anyone think of a good way to allow this class to sometimes be populated from the Advantage database and sometimes the web database? It's not just a matter of connection strings, because they have two very different methods of access (even aside from the reflection). I considered adding [Web("id")] type tags to the Advantage tags, and only putting them on the fields which exist in the web database to designate its columns, then having a switch of some kind to control which set of logic is used for reading/writing, but I have the feeling that that would get painful (Is this method web-safe? How do I set the flag before instantiating it?). So I have no ideas I like and suspect there's a solution I'm not even aware exists. Any input?
I think the fundamental issue is that you want to put business logic in the Warranty object, which is a data layer object. What you really want to do is have a common data contract (could be an interface in this case) that both data sources support, with logic encapsulated in a separate class/layer that can operate with either data source. This side-steps the issue of having a single data class attempt to operate with two different data sources by establishing a common data contract that your business layer can use, regardless of how the data is pulled.
So, with your example, you might have an AdvantageWarranty and WebWarranty, both of which implement IWarranty. You have a separate WarrantyValidator class that can operate on any IWarranty to tell you whether the warranty is still valid for given conditions. Incidentally, this gives you a nice way to stub out your data if you want to unit test your business logic in the WarrantyValidator class.
The solution I eventually came up with was two-fold. First, I used Linq-to-sql to generate objects for each web table. Then, I derived a new class from AdvantageTable called AdvantageWebTable<TABLEOBJECT>, which contains the web specific code, and added web specific attributes. So now the class looks like this:
[AdvantageTable("warranty")]
public class Warranty : AdvantageWebTable<WebObjs.Warranty>
{
[Advantage("id", IsKey = true)][Web("ID", IsKey = true)]
public int programID;
[Advantage("w_cost")][Web("Cost")]
public decimal cost;
[Advantage("w_price")][Web("Price")]
public decimal price;
public Warranty(int id)
{
this.programID = id;
Initialize();
}
}
There's also hooks for populating web-only fields right before saving to the web database, and there will be (but isn't yet since I haven't needed it) a LoadFromWeb() function which uses reflection to populate the fields.

getter , setter 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.

When should we write static function in asp.net class

I am having asp.net page where i have combo box . I am highly confused that how to fill that combo because i am having two approach
Fetch combobox data : by creating object of my database class. and call function for combobox data.
Fetch combobox data : using static function
When should we create static function and how can we decide whether function should be static or not.
Suppose i need to fill No of people living in city based upon city Id and there is another condition of filter like business group, service group, students.
What is better approach of filling combobox.
Function should be static if it's supposed to be stateless. Simple as that.
You can have a lot of scenario how to fill your combobox.
For example:
You can derive from ComboBox and you can fill they on on Load event (or on anyone else event, if you want)
You can have classes for combobox fill with same interface (for example: UserConboBoxFiller, InvoiceComboBoxFiller, ArticleComboBoxFiller, etc...)
You can have static methods for combobox fill - as you wrote. It's not wrong, in simple scenarios.
If you have several filter conditions for filling comboboxes, I recomend use the classes for filling:
public interface IComboBoxFiller {
void Fill( ComboBox cbo );
}
public class UsersComboBoxFiller : IComboBoxFiller {
public bool OnlyOnlineUsers {get;set;}
public void Fill( ComboBox cbo ) {
// there is logic for combobox filling
// you can dynamicly generate where condition
// by the "OnlyOnlineUsers"
}
}
You make your functions static if they do not need to work on class instances and access that instance state.
Static classes and functions are of common use in web applications because these applications are mostly stateless working over stateless HTTP. Or at least they mimic statefulness by using some tricks like sessions, cookies or injecting some helper content into HTML. But even so, there is almost no state in PC memory as such - objects are created to serve the request and deleted after the response has been sent. So, classes and functions are mostly there to pack user data and sent it to the database and in reverse direction. Mostly, just dataflow processing.

Categories

Resources