Solved

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

Posted on 2014-04-22
5
1,160 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
  • 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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

746 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now