How to use ADO.net (SqlConnection) in ASP.net MVC3 - asp.net

I am new to MVC3 and could not find a sample that uses SqlConnection with MVC3 to connect to an existing database. All the samples I found like MusicStore and others are using EF.

Read through this tutorial; it shows you exactly how all of the ORM stuff works so you can get going quickly.

From your contour call off to your repository pattern object ex ICustomerRepository.
Your repository calls your data access layer which returns some data transfer object (or some choose a domain object ie Customer)
Then your view model is populated from that object.
Some choose to chop out the transfer objects and send domain objects to the view rather than view models but the recommended approach is view models.
Your sqlconnection code goes in your data access layer. Do not stuff this code into your controller.

Related

ASP.NET Using one controller from another

I am creating an mvc project, for simplification i have two entitys: Movies and MoviesGenre.
I want to display a list of genres and the amount of movies each of them contains.
Now i have a problem with the design. I am not sure who is responsible for it. I solved that by creating a method in MovieController that returns the amount of movies by genre id and created a method on the MoviesGenreController that select all the genres and uses the MovieController(By instantiating an object) method to get their count.
That doesn't seems like good design to me. Which controller is responsible for this? Do I maybe need to create an extra controller for this logic? Thanks.
You need a data layer project which will manage the access of each controller to the underlying database.
I would suggest the following design:
create a library project (DataLayer) project which connects to the database.
Potential methods exposed:
List GetAllGenres();
List GetMoviesByGenre()
You can either inject the DataLayer as a service or just simply allocate a new object in each controller ctor. This is more like a personal preference... The DI approach is more flexible a more in line with the DotNetCore architecture.
Both MovieController and MovieGenreController should use the methods from the DataLayer.

SQL Server 2014 Reporting Services - business object as data source

I'm trying to get reporting services on asp.net working for the first time. I want to use my existing .Net business object library as the datasource. The objects I wish to use as datasets are all collections created using "Inherits List(Of ", eg
Public Class clsBooking
Inherits List(Of clsBooking)
After instantiating a ReportViewer control, I can successfully select my .Net library as the datasource and then a list of datasets appears as expected. I can't work out why some are appearing in the list and not others - they are all created using "Inherits List Of(". (Of course it is the ones I need which aren't appearing!) I can't find any good information on what exactly is required in the business object to make it usable as a dataset, just that it must be Enumerable.
After hours of faffing and frustration, I worked out that objects only appear in the Report Wizard list of available datasets if they contain a constructor without any parameters (ie Sub New()). So even if you only want to use the constructor with the parameters, you still must create a useless waste-of-time parameter-less constructor.

Simulate Database access on .NET

I have an ASP.NET solution that consist of two different projects:
Project One is the ASP.NET pages, javascript and CSS. Project Two is an encapsulated DLL that is reference by project One, and have all the logic for database Accessing.
Basically, project One collect data and creates instances of classes defined on project Two, and call method on those classes that fisically access de database (inside Project Two code) and return object of type List of(ObjectType)
Now I need to send a copy of the project One to a third party programmer, but i don't want to send Databases, so my idea is to create a copy of project Two (a new DLL), that simulates database access but insted of get data from the database returns fixed data (hardcoded) in the exact same format.
So my question is: How can I Hardcode that data on the DLL without having to create object manualy one by one?.
My first attemp is to serialize an object already returned by a database to XML with this code:
Dim sw As New System.IO.StringWriter
Dim ser As New System.Xml.Serialization.XmlSerializer(GetType(List(Of User)))
ser.Serialize(sw, Users)
Debug.WriteLine(sw.ToString)
That creates an string with all the data. But it is possible to re-create the collection from this result? Is there a better way to do this? thanks!!!

How to call stored proc from ASP.Net MVC stack via the ORM & return them in json?

i'm a total newbie with asp.net mvc and here's my jam:
i have a 3 level list box which selection on box A shows options on box B and selection on box B will show the options for box C.
I'm trying to do the whole thing in asp.net MVC and what i see is that the nerd dinner tutorial uses the ORM method.
so i created a dbml to the database and drag the stored proc inside.
i create a datacontext object but i don't quite know how to connect the result from the stored proce which should be multiple rows of data and make it into a json.
so i can keep all the json data inside the html page and using jquery i could make the selection process faster.
i don't expect the data inside the three boxes to change so often thus i think this method should be quite viable.
Questions:
So how do i get the stored proc part
to return the data as json?
i've noticed some tutorial online
that the json return result part is
at the controller and not at the
model end.
Why is that?
Edit
FYI, i find what i mostly wanted to do here.
For the json part, i referenced here.
Return a JsonResult from your controller action. You may need to coerce the result from your stored procedure into a C# class serializable to Json.
Json conversion should be done in the controller because it's not really part of the domain. More a DTO in the MVVM (Model-View-ViewModel) style.

DataTable Wrapper or How to decouple UI from Business logic

I am using web forms, C#, Asp.net.
As we all know, in this model UI and business logic are often mixed in. How do I separate these effectively?
The example I would like to use is:
I have a GridView and a DataTable (GridView binds to the DataTable and DataTable is fed from the stored procedure).
I would like the GridView (UI) and DataTable (business logic) to be decoupled.
Is it worth it to write an wrapper for DataTable? Are there practical patterns that have been proved and tested that you could recommend to be followed?
If someone with experience could shed some light, that would be awesome.
And, as a final note I would like to say that ASP MVC is not an option right now, so don't recommend it.
My database access layer returns a DataTable.
Note that I HAVE to use this database layer as this is a company policy.
I went through this recently while decoupling much the same thing from our UI layer.
You can see my progress here and here.
In my opinion, A DataTable does not represent business logic. Specifically, it's data pulled directly from the database. Business logic turns that data into a truly useful business object.
The first step, then, is to decouple the DataTable from the Business object.
You can do that by creating objects and List<object> that make up DataTables and Collections of DataTables, and then you can make a ListView that displays those Objects. I cover the latter steps in the links I posted above. And the former steps are as easy as the following:
Create a class that will represent your object.
iterate through your DataTable (or DataSet, or however you retrieve the data) and shove those fields into properties of that object (or that List<T>);
return that List to the Gridview or ListView to display.
This way your ListView or Gridview won't be tightly coupled to the method that you are retrieving your data. What happens if you decide to get your data from a JSON query or a XML file later on? Then you'd have to build this into there.
Step 1 - Getting Data From Database
There are multiple methods to get data from a database, there's no way I can go through all of them here. I assume that you already know how to retrieve data from a database, and if you don't, there are quite a few links to follow. Let's pretend you've connected to the database, and are using an SQLDataReader to retrieve data. We'll pick up there.
Class Diagram
Foo
----
id
Name
Description
And here's the method:
private void FillDefault(SqlDataReader reader, Foos foo)
{
try
{
foo.id = Convert.ToInt32(reader[Foo.Properties.ID]);
foo.Name = reader[Foo.Properties.NAME].ToString();
if (!string.IsNullOrEmpty(
reader[Foo.Properties.DESCRIPTION].ToString()))
foo.Description =
reader[Foo.Properties.DESCRIPTION].ToString();
else foo.Description = string.Empty;
}
catch (Exception ex)
{
throw new Exception(
string.Format("Invalid Query.
Column '{0}' does not exist in SqlDataReader.",
ex.Message));
}
}
Once that happens, you can return a list by going through that process in a while loop that targets the SQLDataReader.Read() function.
Once you do that, let's pretend that your Foo being returned is a List. If you do that, and follow the first link I gave above, you can replace Dictionary<TKey, TValue> with List<T> and achieve the same result (with minor differences). The Properties class just contains the column names in the database, so you have one place to change them (in case you were wondering).
DataTable - Update Based on Comment
You can always insert an intermediate object. In this instance, I'd insert a Business Layer between the DataTable and the UI, and I've discussed what I'd do above. But a DataTable is not a business object; it is a visual representation of a database. You can't transport that to the UI layer and call it de-coupled. They say you have to use a DataTable, do they say that you have to transport that DataTable to the UI? I can't imagine they would. If you do, then you'll never be de-coupled. You'll always need an intermediate object in between the DataTable and the UI layer.
I'd start by decoupling the data table right into the trash can. Build a domain layer, and then some type of data access layer which deals with the DB (ORM recommended).
Then build a servicing layer which provides the data to the UI. All business logic should be within the service or the entities themself.
Consider implementing MVP (model view presenter) pattern. It gives you separation of biz logic through presenter interface, which also allow better unit testing capabilities. Your codebehind of aspx page is then just connector of events and getter/setter of properties. You can find it in MS pattern&practices enterprise application blocks (CAB - composite application block - if i'm not mistaking).
You can read more about it here: http://msdn.microsoft.com/en-us/magazine/cc188690.aspx
But also going from DataTable/DataSets to objects (POCO) is preferred.

Resources