I am using Visual Studio 2012 to create an ASP.NET web application. I tried using the Getting Starting with ASP.NET 4.5 Tutorial but it creates a simple local database and all queries are written directly in the code. The database that I am accessing (SQL Server 2008) has fifteen complex stored procedures that I really don't want to have to retype.
Using the DBContext example in the tutorial works fine when just grabbing all of the data from the tables, but how do I use the stored procedures that are in the database? Can someone please tell me the best way to use the stored procedures that already exist?
All of the questions (and answers) I've found so far are dealing with earlier versions of Visual Studio, and although I know that I could use these (since VS 2012 does support the backward compatibility), I want to make the best use of the software that I have and not use "best practices" from VS 2010.
If you can tell me how to use the existing stored procedures, or even direct me to a book, website, or anything else that would show this to me, I would TRULY appreciate it! Happy coding! And thanks for your time!
I had to piece together info from a few different sources, but I was able to get this working. Here are my steps (I may have done more than I needed, but it worked) just in case it may help someone else:
Added a class to my project Called MyContext, and told it was a DBContext and pointed it to my existing database like this: (Please note that I did already have the full Connection String in my webconfig file under .
{
public class MyContext : DbContext
{
public MyContext()
: base("name=MyDatabase")
{
}
}
}
MyDatabase is replaced with the actual name that refers to my database in the connection string of my webconfig file.
I created a class called ProductList which exposes only the fields that are returned by my stored procedure:
{
public class ProductList
{
[ScaffoldColumn(false)]
public int ProductID { get; set; }
[Required, StringLength(100), Display(Name = "Model")]
public string ProductName { get; set; }
}
}
I actually created a user control (.ascx) which is a just a DataReapeater. In the code-behind on the control, right beneather the Page_Load, I created a Method called GetMostPopular:
public IEnumerable GetMostPopular()
{
var db = new MyContext();
IEnumerable result = db.Database.SqlQuery("MostPopularProducts");
return result;
}
Inside the <> of IEnumerable and SQLQuery is the name of the Class I created. It as the exact same fields that will be returned by my stored procedure "MostPopularProducts".
Then in the DataRepeater, I used GetMostPopular as the "SelectMethod":
'><%# Eval("ProductName") %>
5.Then I just dragged and dropped the User Control onto the page where I wanted it to display.
I hope this helps someone else. Happy coding!
I suggest you use the SqlClient, SqlCommand, SqlConnection...
very easy, with organic output!
Related
My first question on SO!
What I'm working on is a Webforms page that's has a lot ASP textboxes, datepickers and dropdowns. Right now I'm using ADO.net for all of these controls to do CRUD operations.
I'm already a great deal into this project, but I can't help wondering if I could be doing this in an easier or more efficient way. So far I'm using the SqlDataReader class for everything.
If someone could break down the different options available to me or point me to some good information, I'd appreciate it. I know it's a pretty broad topic. I'm kind of aware of LINQtoSQL and EntityFramework.
So my question really is: How does ADO.net compare to LINQtoSQL or EntityFramework?
you should read up on one sample each of ADO.NET, Linq 2 SQL and Entity Framework and implement them to know the pros/cons of each. a simple web search should give you samples.
Linq2Sql and EF will require very SQL query writing from you. once you have an initial grasp of these 3 things individually, follow this simple pattern in your code:
define an interface for your data access.
let your code behind (ascx.cs and aspx.cs) work with the interface.
define concrete implementations of the interface based on ADO.NET, Linq2Sql or EF.
e.g.
public interface IRepository
{
MyDto GetData(int id);
// and so on
}
public class EntityFrameworkRepository : IRepository
{
public MyDto GetData(int id)
{
using (var db = new MyDbContext())
{
var myDtoEntity = db.MyDtoEntity.FirstOrDefault(m => m.Id == id);
// extension method to transform DB objects into DTOs
return myDtoEntity.ToMyDto();
}
}
}
// similarly you can do:
public class Linq2SqlRepository : IRepository
{
// so on..
}
// now for all your aspx.cs pages: derive them from a base page,
// and in the base page
// have a variable like this, so that all pages have access to this.
public IRepository Repository {get; set;}
// you can have static instances as well for one time initialization.
// you can initialize the Repository with a particular concrete implementation
// or inject it. (if you're well versed with Dependency Injection)
using the above way, all your code will work off the Interface, and you just need to change one place if you decide to change the implementation.
Here is the scenario, discovered while trying to troubleshoot the same issue in the self hosted designer. Create a library project with a type in it. Mine is this.
namespace RaceEventLibrary
{
public class Registration
{
public string Name { get; set; }
public int Age { get; set; }
public string EventName { get; set; }
}
}
Now create a Workflow 4.5 console app (or service, it doesn't seem to matter). Reference the library project. Put a sequence on the designer and then make an InArgument of this library type, Registration in my case. All is fine, the designer is happy.
Next create another identical project, reference the same library. Now simply open the xaml file from the first project. Boom, it can't find the types.
System.Xaml.XamlException: 'The type ‘InArgument(r:Registration)’ of property ‘registration’ could not be resolved.'
This in the xaml is:
<x:Members>
<x:Property Name="registration" Type="InArgument(r:Registration)" />
</x:Members>
preceded by
xmlns:r="clr-namespace:RaceEventLibrary;assembly=RaceEventLibrary"
With the self hosted designer I have been finding many variations of this issue and have tried various ways to get the library assembly loaded into the designer, but no joy.
Any suggestions of how to correct this?
WF4 has it own ways of loading assemblies that is not always exactly the same as the standard .NET framework. Ron Jacobs did an interesting number of posts on that, see here for a start.
You don't mention how you actually load the workflow into the WorkflowDesigner. There are several ways of doing this. When using the ActivityXamlServices.CreateBuilderReader() you can specify using the XamlSchemaContext what assemblies are required. That should let you load the workflow.
I have binary data in my database that I'll have to convert to bitmap at some point. I was thinking whether or not it's appropriate to use a repository and do it there. My consumer, which is a presentation layer, will use this repository. For example:
// This is a class I created for modeling the item as is.
public class RealItem
{
public string Name { get; set; }
public Bitmap Image { get; set; }
}
public abstract class BaseRepository
{
//using Unity (http://unity.codeplex.com) to inject the dependancy of entity context.
[Dependency]
public Context { get; set; }
}
public calss ItemRepository : BaseRepository
{
public List<Items> Select()
{
IEnumerable<Items> items = from item in Context.Items select item;
List<RealItem> lst = new List<RealItem>();
foreach(itm in items)
{
MemoryStream stream = new MemoryStream(itm.Image);
Bitmap image = (Bitmap)Image.FromStream(stream);
RealItem ritem = new RealItem{ Name=item.Name, Image=image };
lst.Add(ritem);
}
return lst;
}
}
Is this a correct way to use the repository pattern? I'm learning this pattern and I've seen a lot of examples online that are using a repository but when I looked at their source code... for example:
public IQueryable<object> Select
{
return from q in base.Context.MyItems select q;
}
as you can see almost no behavior is added to the system by their approach except for hidding the data access query, so I was confused that maybe repository is something else and I got it all wrong. At the end there should be extra benifits of using them right?
Update: as it turned out you don't need repositories if there is nothing more to be done on data before sending them out, but wait! no abstraction on LINQ query? that way client has to provide the query statements for us which can be a little unsafe and hard to validate, so maybe the repository is also providing an abstraction on data queries? if this is true then having a repository is always an essential need in project architecture!! however this abstraction can be provided by using SQL stored procedures. what is the choice if both options are available?
Yes, that's the correct way: the repository contract serves the application needs, dealing ony with application objects.
The (bad)example you are seeing most of the time couples any repository implementation to IQueryable which may or may be not implemented by the underlying orm and after all it is an implementation detail.
The difference between IQueryable and IEnumerable is important when dealing with remote data, but that's what the repository does in the first place: it hides the fact you're dealing with a storage which can be remote. For the app, the repository is just a local collection of objects.
Update
The repository abstracts the persistence access, it makes the application decoupled from a particular persistence implementation and masks itself as a simple collection. This means the app doesn't know about Linq2Sql, Sql or the type of RDBMS used, if any. The app sends/receives objects from the repo, while the repo actually persists or loads objects. The app doesn't care how the repo does it.
I consider the repository a very useful pattern and I'm using it in every project, precisely because it marks the boundry between the application (as the place where problems and solutions are defined and handled) and storage/persistence where data is saved.
You can make you repository a generic one and can get mode value out of it. And make sure you are using an Interface (IItemRepository ) to access repositories in manager layer so that the you can replace your repositories with some another data access method using new repository implementation. Here is an good example how to do this.
I'm trying to create a data access later using System.DirectoryServices. I'd like to use the MVC 2 framework and have all my views be mostly strongly-typed. Does anyone know any good way to this?
For example I started creating a Group Entity:
public class Group
{
public string DistinguishedName { get; set; }
public string GroupName { get; set; }
}
And an abstract interface:
public interface IGroupRepository
{
List<Group> Groups { get; }
}
I am confused about developing the GroupRepository using the system.directory services. Connecting to a SQL database is easy there are examples everywhere but I have no been able to find any using the System.directory sevices in conjunction with a class using MVC. Has anyone tried to do something like this? Any great would be
If you're on .NET 3.5 (and if you use MVC 2, chances are good you are), you should check out the new System.DirectoryServices.AccountManagement namespace which brings you lots of strong .NET classes and types for many of the directory objects you're dealing with on a regular basis - no need to re-invent the wheel (yet again!).
Check out this great article in MSDN magazine on how to use this S.DS.AM namespace:
Managing Directory Security Principals in the .NET Framework 3.5
Update: for reasons I don't totally understand, the simple approach of using a UserPrincipal as a model for a ASP.NET MVC view doesn't work - it seems as if ASP.NET MVC cannot "find" any properties on that object.
So the approach would have to be to do something like this:
grab your UserPrincipal (or DirectoryEntry) from Active Directory
define a separate ViewModel - this is just a class that holds properties, like first name, last name and so forth
you can either fill that ViewModel class yourself, or you can grab some help like AutoMapper to make mapping from UserPrincipal (DirectoryEntry) to your ViewModel easier
then display (or edit) your ViewModel class in a standard ASP.NET MVC view
handle any possible updates by transferring any changes back from the ViewModel to the "proper" object and persisting that object
It's a bit more involved than I'd like it to be - but I quite honestly don't see how else you can do this otherwise.
I have an ASP.NET project that uses XML Serialization for the main operation for saving data. This project was to stay small relative to size of data. However, the amount of data has ballooned as it always will and now I'm consider moving to a SQL based alternative for managing the data.
For now I have multiple objects defined that are simply storage classes for saving my data for the project to work.
public class Customer
{
public Customer() { }
public string Name { get; set; }
public string PhoneNumber { get; set; }
}
public class Order
{
public Order() { }
public int ID { get; set; }
public Date OrderDate { get; set; }
public string Product { get; set; }
}
Something along these lines although not so rudimentary. Migrating to SQL seems to be a no-brainer and I've landed on using MySql because of the free availability of the service. What I'm running into is that the only way I can see to do this now is to have a solution where there is a storage class, Order, and a class built to Load/Save the data, OrderIO.
The project relies heavily on using List<> to populate the data fields on the page. I'm not using any built-in .NET controls such as DataGrid to assist in displaying the data. Simple TextBox or ComboBox controls that are populated on Page_Load.
I'm aware it would make better sense to pick a way in which the data fields could bind to the SQL through a Repeater but I'm not looking at a full redesign, just a difference on the infrastructure to manage the data.
I would like to be able to create a class that can return an object similar to what I'm dealing with now, such as List<>, from the SQL statements I'm executing. I'm having some trouble getting started on the best method of approach.
Any suggestions on how best to Load/Save this data using SQL or some tutorials on ideas using the .NET framework would be helpful. This is quite a generalized question but I'm open to most ideas. Thanks.
What you need is a Data Access Layer (DAL) that takes care of running the SQL code and returning the required data in the List<> format that you require. I would definitely recommend you read the two series of articles by Imar Spaanjar on Building a N-Layer Application. Note that there are two sets of series, but I linked to the second set, because it contains links to the first one.
Also, it might be beneficial to know that Sql Server 2008 R2 express edition is free to use, but has a limit of 10 GB per database. I am not saying that you shouldn't use MySQL, but just wanted to inform you in case you didn't know that there is a free edition of Sql Server available.