Solved

How to implement the Repository Pattern for Asp.Net web forms

Posted on 2014-04-22
5
1,304 Views
Last Modified: 2014-04-30
Experts, I need assitance with implementing the Repository Pattern for Asp.Net web forms.  I'm prohibitted to use the MVC design.  The goal is for the UI to produce a plain text report via Sql database values.  Below are my codes.  I've been trying to gain success for over a week with no luck.  Obviously I'm doing something wrong.  Please Help.

The application is separated in layers described below.

Class Library
  BLL
  DAL
  MODEL
UI Project

IDisaggregatedRepository.cs
namespace Cot.Class.BLL
{
    public interface IDisaggregatedRepository
    {
        

        IEnumerable<DisaggregatedReport> GetAgricuture(string N00);
        IEnumerable<DisaggregatedReport> GetPetroleum(string n10);               
    }
}

Open in new window



RepositoryFactory.cs
namespace Cot.Class.BLL
{
    public class RepositoryFactory
    {
        public static IDisaggregatedRepository GetRepository(string repositoryType)
        {
            IDisaggregatedRepository repo = null;

            switch (repositoryType)
            {
                case "Agriculture": repo = new DisaggregatedRepository();
                    break;
                case "Petroleum": repo = new DisaggregatedRepository();
                    break;
                case "Natural Gas": repo = new DisaggregatedRepository();
                    break;
                default:
                    throw new ArgumentException("Invalid Repository");
            }

            return repo;
        }
    }
}

Open in new window



CotDbContext.cs
namespace Cot.Class.DAL
{
    public class CotDbContext : DbContext
    {
        public CotDbContext()
            : base("DbConnectionName")
        {
            Database.SetInitializer<CotDbContext>(null);
        }

        public DbSet<DisaggregatedReport> DisaggregatedReport { get; set; }
    }
}

Open in new window



DisaggregatedRepository.cs
namespace Cot.Class.BLL
{
    public class DisaggregatedRepository : IDisaggregatedRepository
    {

        private CotDbContext dataBase = new CotDbContext();
                
        public IEnumerable<DisaggregatedReport> GetAgricuture(NOO)
        {
            //throw new NotImplementedException();

            List<DisaggregatedReport> agriDisagRpt = new List<DisaggregatedReport>();
            var rptValue = from agrig in agriDisagRpt
                           where agrig.OpenInterest == "N00"
                           select agrig;
            return rptValue.ToList();

            //return dataBase.DisaggregatedReport
            //    .Where(a => a.OpenInterest.Equals("N00"))
            //    select a;

            //using (var agriDb = new CotDbContext())
            //{

            //    var dataAgriReport = agriDb.DisaggregatedReport.ToList();

            //    var AgriRpt = new List<DisaggregatedReport>();
            //    foreach (var reportValue in dataAgriReport)
            //        AgriRpt.Add(new DisaggregatedReport
            //        {
            //            OpenInterest = reportValue.OpenInterest
            //        });

            //    return AgriRpt
            //    .Where(a => a.OpenInterest.Equals("N00"));
            //}


        }

        public IEnumerable<DisaggregatedReport> GetPetroleum(string n10)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<DisaggregatedReport> GetNaturalGas(string n13)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<DisaggregatedReport> GetElectric(string n16)
        {
            throw new NotImplementedException();
        }

        public IEnumerable<DisaggregatedReport> GetOthers()
        {
            throw new NotImplementedException();
        }
    }
}

Open in new window



DisaggregatedReport.cs
namespace Cot.Class.MODEL
{
    public class DisaggregatedReport
    {

        public int MarketCode { get; set; }               

        public string OpenInterest { get; set; }

        public decimal ProducerPosLong { get; set; }
        public decimal ProducerPosShort { get; set; }               

    }
}

Open in new window



Default.aspx.cs
namespace COT.UI
{

	protected void CreateFirstReportsButton_Click(object sender, EventArgs e)
        {

            CreateReport("Agriculture");
            
        }


	protected void CreateSecondReportsButton_Click(object sender, EventArgs e)
        {

            
            CreateReport("Petroleum");
            
        }

protected void CreatReport(string repositoryType)

{
	
	if (repositoryType == "Agriculture")
		{
			string agricultureFilename = "Agriculture.txt";
        		string filename = agricultureFilename;
			IDisaggregatedRepository repository = RepositoryFactory.GetRepository("NOO");
			 WriteDisplayReport(filename, repository);

		}
	elseif repositoryType == "Petroleum"
		{
			string agricultureFilename = "Petroleum.txt";
        		string filename = agricultureFilename;
			IDisaggregatedRepository repository = RepositoryFactory.GetRepository("N10");
			 WriteDisplayReport(filename, repository);
		}

		

}


protected void WriteDisplayReport(string filename, IDisaggregatedRepository repository)
        {
		using (FileStream fileStream = new FileStream(Server.MapPath(@"~/Includes/") + filename, FileMode.Create))
			{
				 using (StreamWriter writer = new StreamWriter(fileStream))
                			{
						string row01 = String.Format("{0, -10}{1, 23}{2, 120}{3, 3}", "Blah", "Blah", ...)
						string row02 = String.Format("{0, 3}{1, 3}{2, 8:0,0}{3, 3}", repository.someClassProperty1, repository.someClassProperty2, ... )

						 writer.Write(row01);
                        			 writer.WriteLine();
                        			 writer.WriteLine(row02);
						 writer.Close();
					}
			}
	}

}

Open in new window



Thank you for your help.
0
Comment
Question by:iNetBlazer
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
5 Comments
 
LVL 25

Expert Comment

by:apeter
ID: 40018659
This link should give you good start.  http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

At the end you should be writing a generic repository and unit of work class .
0
 

Author Comment

by:iNetBlazer
ID: 40020093
apeter,

I'm using Web Forms not MVC.  How can this be done in web forms?  How to I call the repository from the UI?  If I new up the "List<T>" I still can't see the object model.

example:

from a method in the UI

List<ModelName> variableName = new List<ModelName>();
variableName.whatever  is not showing the model/object properties.
0
 

Accepted Solution

by:
iNetBlazer earned 0 total points
ID: 40023201
I solved this myself...  I need to use the "foreach" loop with the List<T> to get each value in the collection vs trying to get each value like you would if you instantiate a class object.   I didn't need to know how to set up a repository.  I need to learn how to get the values after the repository (see my above code blocks).  I guess my question title is little misleading.  Should be titled  "How to get the Repository values in Asp.Net web form UI"

example:

IDisaggregatedRepository repository = new DisaggregatedRepository();

protected void WriteDisplayReport(string filename, IDisaggregatedRepository repository)
{

string item1
string item2

(Incorrect Logic - doesn't work)
  item1 = repository.whatever1
  item2 = repository.whatever2
etc.

vs

(Correct Logic - works good)
List<ModelName> variableName = new repository.getValues();
foreach (var value in variableName)
{
   item1 = value.whatever1
   item2 = value.whatever2
   etc.
}


}

Refer to the above "Default.aspx.cs" code block.  There is where my incorrect logic is located.

I now realize that I have to use the "foreach" in most sinarios to get each value within the collection.

Thank You
0
 

Author Closing Comment

by:iNetBlazer
ID: 40031570
As stated in the answer I need to use the "foreach" loop with the List<T> to get each value in the collection vs trying to get each value like you would if you instantiate a class object.

I now realize that I have to use the "foreach" in most sinarios to get each value within the collection via List<t> along with the IEnumerator<T> within the Repository class.

In my initial opening question, the goal was for the UI to produce a plain text report via Sql database values through a repository class object.

Thank you
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question