How to do backend coding of HTML element in Visual studio? - c#

Hi after creating a button in HTML in Visual studio, how can i do its backend c# coding? Normally while using webforms double click will open coding class but how to acheive this in Visual studio for HTML element?

I think you can use the MVC pattern. To be more familiar with, you can read this documentation https://www.asp.net/mvc.
Few words about MVC pattern:
Define MVC in layman’s terms
Remember you’re technically minded and close to the code. MVC to you
is as clear as day, but saying to the business ‘Model, View,
Contoller’ could give them the impression that you are suffering from
some form tourette syndrome. MVC won’t mean much to the business even
after you define them in relation to the code. To get the business to
understand why this is the answer and least of all what it is, can be
more of a task than expected in my experience. Even some fellow
developers have difficulty understanding this on occasion.
To get the listener to understand what MVC is and why it works what I
have tried in the pass is to apply MVC to a different industries where
the listeners have had more involvement. An example that has worked
for me in the past in a comparison to the property or even the
vehicles. Most people have had dealing’s with builders, carpenters,
plumbers, electricians or have watched the flood of property shows on
the TV. This experience is a good platform to use and to explain why
separation such as MVC works. I know you’re probably thinking that
won’t work as it’s not the same as in software, but remember you’re
not trying to train the business to become developers or have an in
depth understanding of MVC, simply explaining to them that separation
in production is required and that’s what an MVC structure offers.
To give an example of how you could describe this I have very briefly
explained how separation works in property. Keep in mind this is
focused on using the system not developing which could be a completely
different angle of explanation.
View
The view in MVC is the presentation layer. This is what the end user
of a product will see and interact with. A system can have multiple
views of all different types ranging from command line output to
rendered HTML. The view doesn’t consist of business logic in most
clear designs. The interface is fit for purpose and is the area of
interaction. Therefore you could simply output HTML for consumers to
interact with or output SOAP/XML for businesses to interact with. Both
use the same business logic behind the system otherwise known as the
models and controllers.
In the world of property you could think of the view as the interior
of a property or the outer layer of a property that the inhabitants
interact with. The interior can be customised for purpose and the same
property can have many different types of tenants. For example a
property of a particular design could contain residential dwellings.
The same internal space could easily be used as office space, where
although in the same property has a different purpose. However the
property structure is the same. Therefore the environment in which the
users interact does not interfere with the structure of the building.
Controllers
The controller is where the magic happens and defines the business
application logic. This could be where the user has sent a response
from the view, then this response is used to process the internal
workings of the request and processes the response back to the user.
Taking a typical response where a user has requested to buy a book.
The controller has the user id, payment details, shipping address and
item choice. These elements are then processed through the business
logic to complete a purchase. The data is passed through the system
into the model layer and eventually after the entire request satisfies
the business definitions, the order is constructed and the user
receives their item.
If we compare this to a property, we could compare the ordering of a
book online to turning on a light switch. A tenant will flick the
switch to on just like ordering a book. The switch itself is an
element in the view layer which sends the request to the controller
just like clicking a checkout button on a web site. The business logic
in this case is what the electrician installed and are embedded within
the property designs. The switch is flicked, which completes the
circuit. Electricity runs through all the wires including the fuse box
straight through to the light bulb. Just like the user receiving a
book, in this case the tenant receives light. The whole process behind
the scenes involving the electricity cabling is not visible to the the
tenant. They simply interact with the switch within the space and from
there the controller handles the request.
Models
The models in MVC are the bottom most layer and handle the core logic
of the system. In most cases this could be seen as the layer that
interacts with the data source. In systems using MVC, the controller
will pass information to the model in order to store and retrieve
data. Following on from the example above controller definition, this
is where the order details are stored. Additional data such as stock
levels, physical location of product of the book amongst many things
are all stored here. If that was the last book in stock ordered, the
next request for this item may check if it’s available and disallow
the order as the item is no longer available.
Sticking with out example of turning on a light switch, this level in
our structure could be the electricity supply. When the tenant flicks
the switch, the internal circuit must request electricity to power the
request which is similar when the user requested data from the
database, as in data is needed to process a request. If the dwelling
isn’t connected to an electric supply, it cannot complete the process.
Business benefits from using MVC
After you get the message across explaining what MVC is, you will then
have to see what benefits can be obtained from it. I’m not going to go
into a huge amount of detail here are I’m sure you can apply benefits
more accurately which are directly related to you actual situation. To
list just some of the common benefits of an MVC based system here are
a few examples:
Different skill levels can work on different system levels. For example designers can work on the interface (View) with very little
development knowledge and developers can work on the business logic
(Controller) with very little concern for the design level. Then they
simply integrate together on completion.
As a result of the above separation projects can be managed easier and quicker. The designer can start the interfaces before the
developer and vice versa. This development process can be parallel as
opposed to being sequential therefore reducing development time.
Easy to have multiple view types using the same business logic.
Clear route through the system. You clearly know where there different levels of the system are. With a clear route of the system,
logic can be shared and improved. This has added security benefits as
you clearly know the permitted route from the data to the user and can
have clear security checks along the route.
Each layer is responsible for itself. (Relates to point 1) This means that you can have clean file structure which can be maintained
and managed much easier and quicker than a tightly couple system where
you may have lots of duplicate logic.
Having a clear structure means development will be more transparent which should result in reduced development time,
maintenance problems and release cycles if applied properly.
Source: http://www.strongandagile.co.uk/index.php/a-really-simple-explanation-of-mvc/

Another option is keep programming using WebForms, for that, you have to choose the right application:

Related

Understanding application flow with MVVM

I am having a hard time understanding how MVVM is used in case of more complex applications. All the examples I can find are extremely basic Apps.
Let's say I have a "Package Delivery" application. To perform a delivery I have to do 3 steps:
Scan the package
Enter any damages or problems with the package
Let the recipient sign on the device
All this information gets validated on the device and then sent to the backend.
In MVC I would implement this like this:
The DeliveryController handles all of the logic. This includes navigation between pages, fetching of API data and validating all of the data once it is all collected.
The controller acts as the "Connection" between the Views and collects all the information and brings it together.
But how would this be done in MVVM? Where would all the data be brought together? Most implementations of MVVM I can find do something like this:
In this, the data entered in each View would have to be passed to the next ViewModel until the end of the chain is reached. At that point the SignatureViewModel would do the validation and make the API call. That seems very weird and like it would get very confusing, since data would just be "passed through" multiple ViewModels just to have it at the end of the chain.
Another option I see would be that each ViewModel handles it's own data:
Here for instance the DamagesViewModel would validate and send the data it's own View handles. The big issue with this is that data does not get sent as a whole. Also there can not be any validation of the entire data before it is sent.
My last idea would look like this:
This adds a DeliveryViewModel that essentials acts like the DeliveryController does in MVC. It would handle which ViewModel to navigate to next, handle what API calls to make and validate all the data once it is entered.
To me (as someone who has mostly used MVC) this last options seems most sensible. But I also feel like it might miss the point of MVVM.
How is this usually done in MVVM? I would really appreciate any pointers. Links to articles that explain this well are much appreciated.
Also if anyone knows of any publicly available repositories or projects that have this kind of pattern in them, I would love to see them.
Even when using MVVM I still use some form of a controller and consider ViewModels as basically transformation of data to facilitate the view.
So for me there is still a service or controller layer that completely separates the middle and back end tier from the rest of the architecture.
View models come into play depending on the consumer/app - fetches data from the service tier, transforming the data, validating etc for the purpose of a consumer/app/etc.
I have struggled quite a bit with the same thing. Especially since I’ve used MVC quite a lot.
I think the most important thing to consider is that MVVM is not meant to solve exactly the same things as MVC. You can still implement a controller outside of this pattern to complement it. It also changes quite a lot the general design of the application.
One mean to do it that I have used is to implement the controller as a singleton that can be shared between VewModels. This controller can per example be injected into the ViewModels using dependency injection.
Viewmodels could then for exemple subscribe to events coming from the controller to update.
But this is one way to solve this problem among others.
MVVM is a way to organize code. It’s one way to separate your user interface from your logic.
I have found a blog where you can have a look where MVVM architecture is described perfectly.Though here writer demonstrates MVVM for windows form app but at least you can get some idea about architectural design of MVVM.
https://scottlilly.com/c-design-patterns-mvvm-model-view-viewmodel/
Also please have a look into this repo.
https://github.com/MarkWithall/worlds-simplest-csharp-wpf-mvvm-example

Which part of mvc design pattern represents the business logic?

I am a little confused about the definition of the business logic in programming because I used to develop without paying an attention to any of these terminologies but now I want to be a good developer.
While I was reading in Wiki about the definition of the business logic I have read the following definition:
In computer software, business logic or domain logic is the part of the program that encodes the real-world business rules that determine how data can be created, displayed, stored, and changed.
and in another website I have read the following definition with example:
Business logic is that portion of an enterprise system which determines how data is:
Transformed and/or calculated. For example, business logic determines how a tax total is calculated from invoice line items.
Routed to people or software systems, aka workflow.
So I am wondering about which part of the MVC represents the business logic, is it the controller or the model or another part could be in the MVC?
I know that the controller is responsible for sending commands to the model but is it responsible for applying the rules of the business?
For example let's take the above example of the tax:
Suppose that we got the invoice data from a form in a view, the data will be directed to the controller but where the tax will be calculated, will we calculate it in the controller or will we ask for the help of an external class to compute it or will we compute it in the model before updating the database?
Could Example would be appreciated.
You can put the tax calculation logic in the Controller, but you're better off putting it in the Model as it is more loosely coupled. It is reasonable to want to calculate tax on lots of pages, so don't put it in lots of controllers, put it in a model that can be re-used.
If you hear someone talking about "Fat" Controllers vs "Thin" Controllers, that is what they're talking about. Most devs will advocate having very little code in their controllers (making them "thin") and really just acting as a relay/orchestrator off to the Model.
I do think the term Model is a bit confusing though because in Service Oriented Architecture (and functional languages for that matter), they stress trying to have "dumb" objects that don't have any functionality and they frequently refer those dumb objects as "Models". But when it comes to MVC, the "Model" really refers to the Business Model, which incorporates dumb objects that hold values AND the services that work on top of them.
In Enterprise software development, must of time we use N-tier applications. They are 3 or more tiers.
1- Data tier:
2- Application tier (business logic, logic tier, or middle tier)
3- Presentation tier: it is a layer which users can access directly such as a web page, including simple control and user input validation or an operating systems GUI. , .
MVC is one of the seminal insights in the early development of graphical user interfaces, and one of the first approaches to describe and implement software constructs in terms of their responsibilities
This said that MVC is use as a presentation layer. They are others like MVP, MVVM..
Sometime time in small application, an MVC structure is use to separate layer where the model is use as data layer, the controller as Logic layer.

Complex presentation logic same as domain logic in layered application

I write layered application with complex domain under the hood. On the server side, there is a complex class document with, for example, Price attribute. Price is calculated by strategy-pattern classes like ManualEnteredPrice, DistributedPrice, DiscountedPrice and others.
In unit-tests, everything is OK, price is calculated, documents load and store in the database and so on.
Now I would write rich client (winforms) and web portal (javascript) for manipulating documents. I use DataTransferObjects for projects and pass data through WCF from the service layer for the client. In client, I build some kind of viewmodels (bindings in forms and knockout in web) from data transfer objects. And I have to write again the price calculation logic for presentation purpuses. Some radiobuttons for strategy choosing, some controls for data entering and similar Price-strategy-classes for calculating price to display it. And then, when I pass DTO back to the server, I don't use calculated price, because I cannot trust to its value. I must fill some fields in the document and recalculate Price again.
So, I have two different class hierarchies, doing the same things - price calculation.
Is this a correct? Maybe there is another approach? This is very often the situation, when same logic is in the domain and on the client. How do you project this architecture?
I cannot reuse domain in client, because client's classes have some differing fields or additional fields or behavior.
I cannot pass only price calculation to the service layer, because it depends on document state, status, many other document contents. Should I pass whole document for price recalculation to service and then receive and set price in viewmodel?
How do you implement the presentation logic, that is same as domain logic?
I think you got the right approach. As you probably understand, making an architecture decision has some trade-offs. Following this specific approach, you have many benefits (data integrity, separation of concerns, minimum code dependencies etc). On the other hand, you repeat a lot of logic and you think that perhaps this is not very easy maintainable.
I would choose to follow your approach because I suppose that the only dependency between the layers is logical. This logical dependency cannot be thrown away. On the other hand, following your architecture has minimized the code dependencies, which is the primary concern of any software development architecture.
Hope I helped!

Making a Saas MVC App...need customer specific views, resource files, and logic

I am building a hosted business SaaS application using MVC 4/C# 4. I'd need to have customer specific resource files, css, views, and business logic that leverage a base code layer as much as possible. How would each of these (resource files, css, views, logic) need to be structured to accomplish this?
I realize this is probably a very in depth answer...but I have no idea where to start or what to search for to begin to research this. Any pointers so I can research further?
Here are my initial thoughts on each:
Views
Use a Switch statement based on user to return different views.
CSS
Use switch statement in view to specify which css to load
Resource Files
I'm not using them now but need to implement, so not sure exactly how they work. From what I've seen you can specify a resource file at the class MetaData level, which is a compile time thing. Not sure how you would change this at the user level. I can see here, how to change it based on culture...but not by a user profile attribute (like the company they belong to).
This looks like a start...will review more.
Business Logic
In my services layer, I could implement switch statements...but that seems messy. Is there a way to create a new classes that override the base classes but only for certain users? Or putting these in a separate project/dll and only using that dll reference for a certain user?
I used to work on the IBM iSeries, and they had the concept of a library path that could be set by user at login. You'd have a custom code path that overrode the base code path libraries. Is there anything similar in MVC?
Data Localization
In my database, I have a table for Orders and another for OrderStatuses, which may be displayed in a drop down for the user to select a status. These statuses may be 'Open' and 'Closed'. But another customer may want that in Spanish...How would you handle this?
Any other considerations I am missing?
Use switch statement
Any time someone is writing object-oriented code and mentions a switch statement to control variable requirements, alarm lights begin to flash.
When you have similar but different requirements, polymorphism is your friend.
Without knowing full details of your requirements it is difficult to provide a specific answer, but consider using the factory pattern / dependency injection to provide objects appropriate to a specific user (or more probably, to the company associated with a specific user).
UI Layer
Generally speaking you could use a factory to return controller instances, based on a common subclass, that implement requirements for a specific user/customer and return views appropriate to that user.
I'm not well enough versed in the specifics of wiring routes in ASP.Net MVC to suggest how specifically to set that up, but it feels like the right approach. Perhaps another poster can shed more light.
Business Logic
This is a classic use of polymorphism, when requirements vary significantly. Alternatives to per-customer classes include configuration-driven behavior and rules engines. The best choice depends on your specific sitation.
Data Localization
Things like order status in the DB should not be bound to a text like 'Open'. They should be bound to a binary representation (e.g. an INT). Leave it to the View to translate that meaning into something specific to the user's language.
In a SaaS application we have developed we have clients who have their own private domains so being able to support something like that was a must. We had to be able to support:
www.mycompany.com/u/clientname
clientname.mycompany.com
www.clientname.com
On of the things we considered was how we could use a single deployment/code base to handle all of these clients. What we ended up with was a Base system that could be extended through the use of "plugins" which are basically class libraries named "APP.Clients.{ClientName}".
We wrote a custom ViewEngine that allows us to make use of these plugins to load Views, Controllers and even Controller Actions from the clients custom plugin to over-ride the base site.
What we ended up with is similar to what people call "portable areas" or basically external views and controllers in an Assembly.
Clients can share a common "network" database or they can be rolled off in to their own database. Most all of the config comes from reading the current URL and having logic that can determine which "client" it is and loading their settings and processing their customization.
Being able to load the client views required adding in additional search locations for Master Pages, Views and Partial Views (why we have a custom ViewEngine).
There is no simple answer and what works for one SaaS project may not work exactly the same for another. Your architecture will likely be similar but your business needs will dictate where your project takes you!

multi tenant or multi instance application on intranet

I have an existing MVC app which will be utlized by another user group in the near future. Both the existing and new user group/program will have independant data. I was just thinking to add flags in the tables to distinguish between the two user group/programs and do some routing when they access the application to pull up respective data.
Now when it comes to code customization, for instance one group/program wants to have extra fields on a page which the first group does not want or the process flow of the application is seperate between the two user groups.
If the above two scenarios will occur frequently, should I just do a new web and database instance rather than customizing the code for each program/user group. This way both of my customers/user groups will have flexibility to add different logic/fields to the application.
The only con I see with the non-multi tenant approach is the time effort by the developer to maintain two seperate applications. I am scared of adding contional logic to customize the same code base for each different user group/program. Cost of infrastructure is not an issue. Also I do not forsee this application to be used by more than 2 user groups/programs at any time. So what do you guys think which apporach i should take and why? thanks all in advance
P.S The users arent any ninjas who will try to hack the site to see the other tenants data. They are corporate users. Theyd rather not use this application but its part of the process so they have to use it.
It's worth taking a look at microsoft's article on multi-tenancy.
I'm also working on trying to design an mvc app with such an architecture where each client can have separate fields and customised screens.
The conclusion that I have come to is that using an IOC container with multi-tenancy support will probably make the whole thing a lot easier.
Autofac has built in multi-tenancy support.
In terms of having logic for clients in each view I believe that if you go down the IOC path you can have a controller for each tenant and in that case hard coding such client specific logic isn't necessarily as bad as it would be having it hard coded all into a shared controller. In essence I believe when writing a component that is for a particular tenant you can switch you mindset to writing as if that tenant was the only one using the system.
The other solution I have landed in for customising views is to use a variation of the RazorGenerator approach for compiled views where I have each tenants views compiled into a separate assembly and have created my own view engine (based on this) where I can swap out the assembly that I look for views in depending on a value in the routing parameters.
Of course I'm still exploring this approach and haven't fully flushed it out in order to find out where it may fall short.
If the difference in the 2 users' requirements is more than 10% of the screens/functionality then you better have 2 databases and apps. If it is expected to be less than 10% then just write separate actions (possibly with different prefixes or suffixes in Action names) for where the functionality differs.

Categories