Use of abstract class in shopping portal - asp.net

I know that my this question may sound pathetic to you but as a beginner in .NET, it means a lot to me.
I just want to know that how can I utilize the concept of Abstract class, virtual class etc. in my shopping cart website. I have read the tutorial out there on internet and I saw some examples too, but those examples are so general that they dosen't fit into real world scenerio like I am searching for a shopping website. Same questions again and again comes to my mind that why to made a class only to give the declaration of methods and property.
I understand that most of you are Gurus of .NET and have ample knowlesge in it but if you could just help me out in thinking the logic behind this i'll be very greatfull.
If possible, please recommend me nice books for asp.net design patterns, from which I can learn design patterns.
Thanks in advance

Your one stop resource and guide is Head First - OOAD.
alt text http://i36.tinypic.com/8y6luo.jpg

If you can't see why to use them then don't for now. Never use a design pattern just for the sake of it.
As for their purpose however, imagine that you want to allow different types of products, but you never have something that is just a "Product" - it's always something specific like a "Book" or "Car". In that case you can put the common properties in an abstract Product class like this:
public abstract class Product
{
/* Abstract Price allows Car/Book to apply their own category discounts */
public abstract decimal Price { get; }
public string Title { get; }
public void AddReview(int userId, string reviewText)
{
/* Add review */
}
public abstract List<Product> Recommendations(int userId);
}
which your Book and Car classes can then extend.

Here is a good design patterns book with examples in C#.
C# 3.0 Design Patterns

Its not ture that for every desing you have to use Abstarct class or define virtual methods.
Basically virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class, and Abstarct keyword enables you to create classes and class members solely for the purpose of inheritance—to define features of derived, non-abstract classes
In your case you can have an abstract class called CartItem which works as a base class for all the types of items you are supposed to support in you cart. All types of items will inherit the CartItem class. You can’t directely create the instance of CartItem class but you can use this as a reference to achieve the Polymorphism.
You can define some concrete methods/properties like ItemId, ItemName, Price etc in the CartItem class which are common to all the types of items and you can also define some of the methods a virtual for which you have a default implementation but the child classes can override the implementation.

Related

Looking to avoid ViewBag usage in MVC 5 - suggestions?

So I have been googling how to remove any and all usage of ViewBags in favour of something more elegant and effective. Unfortunately virtually all of the information I have come across is for prior versions of MVC, and I have yet to find something that both works and is really effective.
One of my primary objective is to be able to populate both the page and the layout at the same time, so that I can add a page title to both the <h2> as well as the <title>. I also want to be able to, if needed, to supply the first paragraph of the body content, which is drawn from the database as a separate column, to the meta-description (this is a special case where all first paragraphs are their own separate entry in the row in the db, purely for the purpose of also acting as the meta-description).
I have run across something that I believe will meet my needs, but I cannot seem to properly implement the fifth code block:
Now create the view base class. You need to create two versions to
have support for typed views.
public class ViewBaseWithLayoutModel : WebViewPage{
public LayoutViewModel LayoutModel {
get { return (LayoutViewModel)ViewBag.LayoutModel; }
}
}
public class ViewBaseWithLayoutModel<T> : WebViewPage<T>{
public LayoutViewModel LayoutModel {
get { return (LayoutViewModel)ViewBag.LayoutModel; }
}
}
Specifically, it is the “create the view base class” that has me tied up in knots -- are they talking about an entirely new section in the project, similar to the Views, Controllers, Models, Extensions, Validators, etc., such that the namespace would be namespace Project.ViewBase {?
And if I can put the fifth code block straight beside another controller like BaseController (inside the Project.Controllers namespace but below the BaseController class in that file), why do both classes throw the errors,
'ViewBaseWithLayoutModel' does not implement inherited abstract member 'WebPageExecutingBase.Execute()'
As well, the sixth code block references
<pages pageBaseType="Namespace.To.ViewBaseWithLayoutModel">
So in the above case would it be 'Project.Controllers.ViewBaseWithLayout'?
Any help would be greatly appreciated.

ViewModel classes VS defining an Exclude Bind list on the domain class

I have a model class named Server, it contains many navigation properties and properties, which I want to prevent users from binding it. So I find two approaches of doing so to avoid over-posting attacks.
The first approach is to go to each model class and define an Exclude Bind list , with all the properties and navigating properties that should not be bind by users , as follow:-
[MetadataType(typeof(TMSServer_Validation))]
[Bind(Exclude = "Technology,IT360SiteID, VirtualMachines, TMSServer1,DataCenter,OperatingSystem,Rack,ServerModel,TechnologyBackUpStatu,TechnologyRole,TechnologyStatu ")]
public partial class Server {
}
}
The second approach is to create a view model class , with only the properties that can be modified by users as follow:-
public class ServerViewModel
{
public int ServerSize { get; set; }
[Required]
public String OperatingSystem { get; set; }
public String Commnet { get; set; }
}
I find that the first approach is faster to implement , as I only need to define the Exclude list, while the second approach will require me to create view-model class for each of the domain classes. So which approach is recommended to use and why ?
Thanks
Over-posting occurs due to the default model binder not knowing which fields you actually included in the form.
It will try to map all values in the request to object. Attackers can use your form to add additional fields to
query strings/form post data and add properties as part of the request. The default model binder won't
know the difference. Your Server class will deactivate once the mapping is complete and the update is processed.
To prevent over-posting, set the annotation to include fields in the binding, or create a ViewModel like you mentioned in your code.
So which approach is recommended to use and why ?
Both annotation and ViewModel allow binding only on specified fields, but when you use ViewModel you will not bind against business objects or entities, and you will only have properties available for the input you expected.
Once the model is validated, you can then move values from the input model to the object you used in the next layer.
k. Soctt Allen has a good article about which approach is better, you can take a look at by the following link:
http://odetocode.com/blogs/scott/archive/2012/03/11/complete-guide-to-mass-assignment-in-asp-net-mvc.aspx
It's difficult to tell without seeing the rest of your code, but in general I'd say using the ViewModel is probably a better approach for the following reasons:
You separate your view from your business logic
It is safer. If in the future someone adds a property on Server and forgets the Bind-exclude, you're exposed to over-binding without knowing it. If you use the ViewModel-approach you have to explicity add new properties
Maybe this question is a little bit ambiguous because the answers are going to be based on opinions or something. But I'll try to answer it the best I can and indeed is kind of my opinion. So this is the way I see it:
First approach (Bind attribute): Is faster to implement because you only need to add on your class the name of the property you don't want to expose, but the problems comes when you want your class to exclude some properties for one feature and other properties for another feature, and you can't add fields and sometimes in MVC, the views need more fields that the ones provided by the model class and then you're gonna need to use ViewBag or something else. This approach is very handy for fast and smalls projects, but I still don't like to use ViewBag (For aesthetics reasons)
Second approach (ViewModels): Is more work, and more time but at the end (again in my opinion) you get a cleaner and ordered code and you don't need to use the ViewBag, because you can have the perfect object to send to the view depending on what this View needs, so if you a have an object with different views, again depending on the needs, they could share the same ViewModel or they could have a ViewModel for each one. If you have a solution or a big web project, this approach is going to be very handy to keep an ordered code.
Let me know.

Adding and removing items dynamically in one View with Entity Framework and MVC

I've been at this same question in different forms now for a while (see e.g. Entity Framework and MVC 3: The relationship could not be changed because one or more of the foreign-key properties is non-nullable ), and it's still bugging me, so I thought I'd put it a little more generically:
I feel this can't be a very unusual problem:
You have an entity object (using Entity Framework), say User. The User has some simple properties such as FirstName, LastName, etc. But it also has some object property lists, take the proverbial example Emails, to make this simple. Email is often designed as a list of objects so that you can add to that object properties like Address and Type (Home, Work, etc). I'm using this as an example to keep it generic, but it could be anything, the point is, you want the user to be able to add an arbitrary number of these items. You should also be able to delete items (old address, or whatever).
Now, in a normal web page you would expect to be able to add these items in the same View. But MVC as it seems designed only makes it easy to do this if you call up an entirely new View just to add the address. (In the template for an Index View you get the "Create New" link e.g.).
I've come across a couple of examples that do something close to what I mean here:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
and
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
The problem is, although the sample projects on these sites work fine, with mock model objects, and simply lists (not an object with a child list), it's a different thing if you actually want to do something with the posted information - in my case save to database through the Entity Framework model. To adapt these cases to that, all of a sudden I'm in a maze of intricate and definitely not DRY code... Juggling objects with AutoMapper and whatnot, and the Entity Framework won't let you save and so on (see above link if you're interested in the details).
What I want to get at is, is it really possible that this is such an uncommon thing to want to do? Update a child collection in the same View as the parent object (such as the email addresses in this case)? It seems to me it can't be uncommon at all, and there must be a standard way of handling this sort of scenario, and I'm just missing it (and no one here so far has been able to point me to a straighforward solution, perhaps because I made it too abstract with my own application examples).
So if there is a simple solution to what should in my view be a simple problem (since the design is so common), please tell me.
Have you tried updating the project at your link to Steven Anderson's blog to bind to a complex object? Create a class in models called Sack and give it a single property and see if you can get it to work.
public class Sack
{
public IEnumberable<Gift> Gifts { get; set; }
}
It only took me a minute to get it up and running as I think you intend. The improvement I would have made next would be to add an HtmlHelper extension that is essentially the same as Html.EditorFor(m => m.SomeProperty), only call it something more meaningful and have it interface with the prefix scope extensions provided in the project.
public static class HtmlExtensions
{
public static IHtmlString CollectionEditorFor<TModel, TValue>(this HtmlHelper html, Expression<Func<TModel, TValue>> expression)
{
if (/* type of expression value is not a collection */) throw new FailureToFollowTheRulesException("id10t");
// your implementation
}
}

abstraction and interface explanation [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
could some body explain me abstraction and interface in asp.net, C# by taking an apprpriate example...pleasse
i am not understanding it for long
I often find the following sample quite illuminating when it comes to explaining this:
Disclaimer: the code examples are written directly into the text, and may contain errors that I have overseen. Please let me know if you find such errors.
Let's say you have a database with a Customer table, and in your code you have a customer class:
class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
In order to provide a mechanism to get customer data from the database, you need to write some class doing that. This can be placed in something called a repository. Now, we don't want our code to rely too much on what exact database we use. It could be SQL server, it could be a text file. So we want an abstraction layer shielding the code from this knowledge. All we need to know is what such a repository looks like:
public interface ICustomerRepository
{
Customer GetCustomer(int id);
IEnumerable<Customer> FindCustomers(string beginningOfName);
}
We can now implement this interface for the data storage that we use:
public class SqlServerCustomerRepository : ICustomerRepository
{
public Customer GetCustomer(int id)
{
using(SqlConnection connection = new SqlConnection(connectionString))
{
// code to fetch data and populate Customer objects go here
}
}
// implementations of other members of ICustomerRepository
// left out to keep code short. Just imagine they are here :)
}
Finally, when we want to use this code, we can have a factory create the concrete ICustomerRepository implementation to use:
public static class RepositoryFactory
{
public static ICustomerRepository CreateCustomerRepository()
{
return new SqlServerCustomerRepository();
}
}
...and in our code where we need the data:
ICustomerRepository repository = RepositoryFactory.CreateCustomerRepository();
IEnumerable<Customer> customers = repository.FindCustomers("A");
This way, there is no hard coupling between the consuming code, and the particular kind of repository in use (except for in the factory method, but that is the one and only place where this knowledge exists). This makes it easy to replace the concrete repository implementation. This is also useful for testing, where you can easily create a mock repository returning hard coded results for given input, so that you can unit test the code that needs data from the repository.
Well abstract classes and interfaces are not strictly asp.net technic they are OOP concept.
Interface
An interface is like a class but all the methods and properties are abstract. An Interface cannot be instantiated like abstract class. All the methods and properties defined in Interface are by default public and abstract.
Interface generally refers to an abstraction that an entity provides of itself to the outside. Interface can help in separating the methods for external and internal communication without effecting in the way external entities interact with the type..
Example:
If you have interface IDoSomething { void Do(); }
The class that implements the interface must provide a body for Do() method e.g.
class SomeClass : IDoSomething
{
public void Do()
{
//body of the method
}
}
The advantage of this is when you make something that need only Do method you pass the interface not the class.
public static void SomeMethod(IDoSomething obj)
{
obj.Do();
}
Now SomeMethod(IDoSomething obj) will work with any class that implements IDoSomething
Abstract Class
An abstract class is a class with at least one method defined as abstract. This type of class cannot be instantiated. An abstract class can have one or more abstract methods and properties and other methods and properties like normal classes.
The idea is the same but in abstract class you can have methods with implemented logic, fields and so on.
Abstraction
Abstraction is the process of hiding how the object is working, and its only showing the information of the object the way we can understand it. Means it represent the essential details with out showing ground details. We putting all variables and method in a class which are necessary.
Eg: Employee and Patient.
Company interested to fill about the Employee details like Name, Address, Qualification, DOB, Age, Mobile, Marks, Experience etc
Hospital interested to fill about the patient details like Name, DOB, Height, Weight, Age, Address, Mobile, Blood Group etc.
Both Company and hospital interested to fill some common fields like Name, Age, DOB, Address, Mobile etc. So we can create a class which consist of common thing that is called abstract class. This class wont be complete but can inherit by other class.
Abstract vs Interface
You cannot create an object of abstract class , but can make derivations of this.
An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.
An abstract class can have abstract members as well non abstract members. But in an interface all the members are implicitly abstract and all the members of the interface must override to its derived class.
Defining an abstract class with all the abstract members is similar to defining an interface. i.e we can say an interface is an abstract class with all the abstract members
Classes may inherit from only one base class, so if you want to use abstract classes to provide polymorphism to a group of classes, they must all inherit from that class.
Abstract classes may also provide members that have already been implemented. Therefore, you can ensure a certain amount of identical functionality with an abstract class, but cannot with an interface.
Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
1). If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
2). If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
3). If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
4). If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.

Best Object layout in ASP.net

What's the best object layout in ASP.net or at least.. what are the advantages and disadvantages of either case:
Public Class Dog
Public Breed as String
Public Type as String
Etc....
OR the use of properties and keeping variables private
Somewhat of a debate among our team about it. Just wanted to hear thoughts.
Never expose fields directly.
Use properties with private backing fields. This allows you to change implementation and to encapsulate logic around getting/setting them.
See what the Visual Basic Team have to say on this.
Also, read about the differences between fields and properties.

Resources