Skip to content
This repository has been archived by the owner on Feb 22, 2021. It is now read-only.

Commit

Permalink
ADO.NET Repository
Browse files Browse the repository at this point in the history
  • Loading branch information
hbulens committed Jun 12, 2016
1 parent adfae78 commit 2e9269e
Show file tree
Hide file tree
Showing 7 changed files with 164 additions and 75 deletions.
80 changes: 6 additions & 74 deletions hbulens.Exam70487.Blobs/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,6 @@ static void Main(string[] args)
Console.WriteLine("Block Blob Sample");
BasicStorageBlockBlobOperationsAsync().Wait();

// Page blob basics
//Console.WriteLine("\nPage Blob Sample");
//BasicStoragePageBlobOperationsAsync().Wait();

Console.WriteLine("Press any key to exit");
Console.ReadLine();
}
Expand Down Expand Up @@ -130,81 +126,17 @@ private static async Task BasicStorageBlockBlobOperationsAsync()

// Download a blob to your file system
Console.WriteLine("4. Download Blob from {0}", blockBlob.Uri.AbsoluteUri);
//await blockBlob.DownloadToFileAsync(string.Format("./CopyOf{0}", ImageToUpload), FileMode.Create);
await blockBlob.DownloadToFileAsync(string.Format("./CopyOf{0}", ImageToUpload), FileMode.Create);

// Clean up after the demo
// Clean up blob
Console.WriteLine("5. Delete block Blob");
//await blockBlob.DeleteAsync();
await blockBlob.DeleteAsync();

// When you delete a container it could take several seconds before you can recreate a container with the same
// name - hence to enable you to run the demo in quick succession the container is not deleted. If you want
// to delete the container uncomment the line of code below.
//Console.WriteLine("6. Delete Container");
//await container.DeleteAsync();
// Clean up container
Console.WriteLine("6. Delete Container");
await container.DeleteAsync();
}

/// <summary>
/// Basic operations to work with page blobs
/// </summary>
/// <returns>Task</returns>
private static async Task BasicStoragePageBlobOperationsAsync()
{
const string PageBlobName = "samplepageblob";

// Retrieve storage account information from connection string
// How to create a storage connection string - http://msdn.microsoft.com/en-us/library/azure/ee758697.aspx
CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create a blob client for interacting with the blob service.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

// Create a container for organizing blobs within the storage account.
Console.WriteLine("1. Creating Container");
CloudBlobContainer container = blobClient.GetContainerReference("democontainerpageblob");
await container.CreateIfNotExistsAsync();

// Create a page blob in the newly created container.
Console.WriteLine("2. Creating Page Blob");
CloudPageBlob pageBlob = container.GetPageBlobReference(PageBlobName);
await pageBlob.CreateAsync(512 * 2 /*size*/); // size needs to be multiple of 512 bytes

// Write to a page blob
Console.WriteLine("2. Write to a Page Blob");
byte[] samplePagedata = new byte[512];
Random random = new Random();
random.NextBytes(samplePagedata);
await pageBlob.UploadFromByteArrayAsync(samplePagedata, 0, samplePagedata.Length);

// List all blobs in this container. Because a container can contain a large number of blobs the results
// are returned in segments (pages) with a maximum of 5000 blobs per segment. You can define a smaller size
// using the maxResults parameter on ListBlobsSegmentedAsync.
Console.WriteLine("3. List Blobs in Container");
BlobContinuationToken token = null;
do
{
BlobResultSegment resultSegment = await container.ListBlobsSegmentedAsync(token);
token = resultSegment.ContinuationToken;
foreach (IListBlobItem blob in resultSegment.Results)
{
// Blob type will be CloudBlockBlob, CloudPageBlob or CloudBlobDirectory
Console.WriteLine("{0} (type: {1}", blob.Uri, blob.GetType());
}
} while (token != null);

// Read from a page blob
Console.WriteLine("4. Read from a Page Blob");
int bytesRead = await pageBlob.DownloadRangeToByteArrayAsync(samplePagedata, 0, 0, samplePagedata.Count());

// Clean up after the demo
Console.WriteLine("5. Delete page Blob");
await pageBlob.DeleteAsync();

// When you delete a container it could take several seconds before you can recreate a container with the same
// name - hence to enable you to run the demo in quick succession the container is not deleted. If you want
// to delete the container uncomment the line of code below.
//Console.WriteLine("6. Delete Container");
//await container.DeleteAsync();
}

/// <summary>
/// Validates the connection string information in app.config and throws an exception if it looks like
Expand Down
98 changes: 98 additions & 0 deletions hbulens.Exam70487.Repositories/AdoRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace hbulens.Exam70487.Repositories
{
public abstract class AdoRepository<T> : IRepository<T>
{
#region Constructor

public AdoRepository(string connection)
{
string conectionString = ConfigurationManager.ConnectionStrings[connection].ConnectionString;
this.Connection = new SqlConnection(conectionString);
}

public AdoRepository(string connection, string table) : this(connection)
{
this.Table = table;
}

#endregion Constructor

#region Properties

private SqlConnection Connection { get; set; }
protected virtual string Table { get; set; }

#endregion Properties

#region Methods

/// <summary>
///
/// </summary>
/// <returns></returns>
public IEnumerable<T> Get()
{
this.Connection.Open();

using (SqlCommand command = this.Connection.CreateCommand())
{
command.CommandText = string.Format("SELECT * FROM {0}", this.Table);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return this.Map(reader);
}
}
}

this.Connection.Close();
}

/// <summary>
///
/// </summary>
/// <param name="filter"></param>
/// <returns></returns>
public IEnumerable<T> Get(Expression<Func<T, bool>> filter)
{
throw new NotImplementedException();
}

/// <summary>
///
/// </summary>
public void Dispose()
{
this.Connection.Dispose();
}

protected T Map(IDataRecord record)
{
T item = Activator.CreateInstance<T>();
IDictionary<string, int> fields = record.GetAllNames();

foreach (var property in typeof(T).GetProperties())
{
if (fields.Select(x => x.Key).Contains(property.Name) && !record.IsDBNull(record.GetOrdinal(property.Name)))
{
property.SetValue(item, record[property.Name]);
}
}
return item;
}

#endregion Methods

}
}
22 changes: 22 additions & 0 deletions hbulens.Exam70487.Repositories/Utilities/AdoNetUtilities.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace hbulens.Exam70487.Repositories
{
internal static class AdoNetUtilities
{
internal static Dictionary<string, int> GetAllNames(this IDataRecord record)
{
var result = new Dictionary<string, int>();
for (int i = 0; i < record.FieldCount; i++)
{
result.Add(record.GetName(i), i);
}
return result;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
Expand All @@ -50,9 +51,11 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AdoRepository.cs" />
<Compile Include="EFRepository.cs" />
<Compile Include="IRepository.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Utilities\AdoNetUtilities.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
Expand Down
18 changes: 17 additions & 1 deletion hbulens.Exam70487.WebApi/Controllers/CustomersController.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using hbulens.Exam70487.Common;
using hbulens.Exam70487.Core;
using hbulens.Exam70487.Core.Repositories;
using hbulens.Exam70487.Repositories;
using System;
using System.Collections.Generic;
Expand Down Expand Up @@ -30,10 +31,25 @@ public CustomersController()
[HttpGet]
public IEnumerable<Customer> Get()
{
IEnumerable<Customer> customers = default(IEnumerable<Customer>);

// *************************************************************************************************************************
// The ADO.NET way
// *************************************************************************************************************************
using (IRepository<Customer> customerRepository = new CustomerRepository("ExamContext"))
{
customers = customerRepository.Get().ToList();
}

// *************************************************************************************************************************
// The Entity Framework way
// *************************************************************************************************************************
using (IRepository<Customer> customerRepository = new EFRepository<Customer>(new ExamContext()))
{
return customerRepository.Get();
customers = customerRepository.Get().ToList();
}

return customers;
}

#endregion Methods
Expand Down
17 changes: 17 additions & 0 deletions hbulens.Exam70487.WebApi/Repositories/CustomerRepository.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using hbulens.Exam70487.Common;
using hbulens.Exam70487.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace hbulens.Exam70487.Core.Repositories
{
public class CustomerRepository : AdoRepository<Customer>
{
public CustomerRepository(string connection) : base(connection, "Customers")
{
}
}
}
1 change: 1 addition & 0 deletions hbulens.Exam70487.WebApi/hbulens.Exam70487.WebApi.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
<Compile Include="Formatters\CsvFormatter.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Repositories\CustomerRepository.cs" />
<Compile Include="Startup.cs" />
</ItemGroup>
<ItemGroup>
Expand Down

0 comments on commit 2e9269e

Please sign in to comment.