C-sharp Cache Image returned from asp.net webapi

Hey folks, well recently i developed some web service that return image as file from a web service method. User pass us a URL like below:

http://www.abc.com/api/downloadfile?fileid=100&type=user

This return image of user with id=100

Lets say we list 100 users on a page, and bind this URL to image src attribute, whenever the page loads, it will make 110 calls to the service and page stays busy until all images are loaded.

To tackle this, all i did was below HIGHLIGHTED IN BOLD:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
        [HttpGet]
        [EnableCors(origins: "*", headers: "*", methods: "get", PreflightMaxAge = 600)]
        [Route("DownloadFile")]
        [Microsoft.AspNetCore.Mvc.ResponseCache(Duration = 259200)]
        public async Task<httpresponsemessage> DownloadFile(int FileId)
        {
            var result = Task.Factory.StartNew(() =>
            {
                var regact = DownloadFileContent(FileId); //returns us the bytes of file based on Id provided.
                return regact;
            });
 
            await result;
 
            if (result.Result == null)
            {
                HttpResponseMessage resultNoFile = new HttpResponseMessage(HttpStatusCode.NoContent);
                return resultNoFile;
            }
            else
            {
                byte[] fileContent = Convert.FromBase64String(result.Result.DocumentBody);
 
                HttpResponseMessage results = new HttpResponseMessage(HttpStatusCode.OK);
                var stream = new System.IO.MemoryStream(fileContent);
                results.Content = new StreamContent(stream);
                results.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(result.Result.MimeType);
 
                results.Headers.CacheControl = new CacheControlHeaderValue
                {
                    Public = true,
                    MaxAge = TimeSpan.FromSeconds(259200)
                };
 
                results.Headers.Add("Cache-Control", "public, max-age=259200");
                return results;
            }
        }
</httpresponsemessage>

Added following attribute to method

[Microsoft.AspNetCore.Mvc.ResponseCache(Duration = 259200)]

and following chunk into the code block.

results.Headers.CacheControl = new CacheControlHeaderValue
{
Public = true,
MaxAge = TimeSpan.FromSeconds(259200)
};

results.Headers.Add(“Cache-Control”, “public, max-age=259200”);

After this first time we load images from service and next time from disk cache.

DateTime Start and End of Day Extension Methods

Another quick post with some useful extension methods for the System.DateTime struct. I’ve been working a lot with the DateTime type over the past couple of weeks. One particular use case has been to pass a “start” and an “end” DateTime to some SQL Server stored procedure. The stored procedure then returns some data based on some timestamp field that falls between the start and end DateTime’s passed in.

In the code I was maintaining, the previous developer had created a DateTime value using DateTime.Now, which returns a DateTime with the time part also populated to the current system time. So when passing this DateTime to the stored proc as a “start” DateTime, the proc was looking from the time-part onwards on the specific day represented by the DateTime. Likewise, when using a similarly created DateTime for the “end” DateTime, the stored proc only returned rows upto the time-part. This was undesired behaviour because the original intention was to retrieve all of the records between two specified days (inclusive of the start and end days).

I decided to tackle this at the application-level. This was mainly to keep the stored procedure flexible so that it can continue to handle retrieval of records at the more granular time level if required. I decided to implement this functionality by adding two extension methods on DateTime, namely, ResetTimeToStartOfDay and ResetTimeToEndOfDay. These return new DateTime values with the time part appropriately set. The idea is to call ResetTimeToStartOfDay on the “start” DateTime and ensure that the returned DateTime is sent to the stored procedure. Likewise, call ResetTimeToEndOfDay on the “end” DateTime. I’ve included the implementation of the two methods below – very simple but useful to have in your library.

public static DateTime ResetTimeToStartOfDay(this DateTime dateTime)
{
   return new DateTime(
      dateTime.Year, 
      dateTime.Month, 
      dateTime.Day, 
      0, 0, 0, 0);
}

public static DateTime ResetTimeToEndOfDay(this DateTime dateTime)
{
   return new DateTime(
      dateTime.Year, 
      dateTime.Month, 
      dateTime.Day, 
      23, 59, 59, 999);
}

The Generic Lazy Type

Lazy<T> is a monad type that was introduced in .NET 4 and provides an alternative mechanism for implementing lazy initialisation. Lazy initialisation is where you intentionally delay the creation of an object that is expensive to create.

You would typically want to use lazy initialisation in scenarios where the object (which is expensive to create) may or may not be used in the execution flow of your program. In this case, it makes sense to only initialise the object if it is required. One reliable place where you may have seen the lazy initialisation tactic being used is in an implementation of a singleton class – which will have a method or property that returns the singleton instance, for example:

public MySingletonClass GetInstance()
{
    if (_singleton == null)
        _singleton = new MySingletonClass();

    return _singleton;
}

The logic before the return statement is an example of lazy initialisation, where the singleton is only instantiated the first time GetInstance is called and never before it. Subsequent calls to GetInstance will then also return the same instance, hence we have an implementation of the singleton design pattern. In this particular case, we don’t know if MySingletonClass is expensive to create, and we don’t particularly care as we’re using lazy initialisation to prevent multiple instances of MySingletonClass from being created.

If we now go back to the mainstream use for lazy initialisation, where we want to delay instantiation of expensive-to-create objects, you could adopt the pattern above where you conditionally instantiate an instance of an object. However, since .NET 4, you have an alternative option with the use of Lazy<T>. An instance of Lazy<T> wraps around your expensive-to-create object, you pass this instance around in your code and when ever the underlying expensive-to-create object is required, you can call the Value property on Lazy<T> which will instantiate the object and return it to you.

The following contrived example should make it more clear. Imagine you have a Customer class and an Order class. A single customer can have many orders, so we’ll make use of composition and have the Customer class support a List of Order objects. The Customer class has one constructor that accepts a customer ID. Using the supplied ID, the constructor then goes and retrieves the orders for the customer from an order repository. Note that in reality your entity classes will usually be dumb and just support getter and setter properties and it’ll be the responsibility of your data access layer/framework (like Entity Framework) to instantiate and populate your entities appropriately. Continuing with our contrived example, our initial attempt may therefore look like:

public class Order { }

public class Customer
{
    public int Id { get; private set; }
    public string Name { get; set; }
    public List<Order> Orders { get; set; }

    public Customer(int id)
    {
        Id = id;
        Name = "Ms Foo Bar";

        // Simulate getting lots of orders from an
        // order repository
        Orders = Enumerable
            .Repeat<Order>(new Order(), 200)
                .ToList();
    }

    public override string ToString()
    {
        return string.Format(
            "I'm customer with id {0}", Id);
    }
}

As the code indicates, it would be expensive to instantiate a Customer object if we didn’t require the order information contained within it. This is where you would apply the concept of lazy initialisation. In this case, we’ll make use of the Lazy<T> type. The following code shows how the Customer class would look if we lazily instantiate the Orders list using Lazy<T>.

public class Customer
{
    public int Id { get; private set; }
    public string Name { get; set; }
    public Lazy<List<Order>> Orders { get; set; }

    public Customer(int id)
    {
        Id = id;
        Name = "Ms Foo Bar";

        Orders = new Lazy<List<Order>>(() => {
            // Simulate getting lots of orders from an 
            // order repository 
            return Enumerable
                .Repeat<Order>(new Order(), 200)
                    .ToList();
            }
        );

        Debug.WriteLine(this);
    }

    public override string ToString()
    {
        return string.Format(
            "I'm customer with id {0}", Id);
    }
}

As you can see, the constructor of the Customer class instantiates an instance of Lazy<T> that wraps around the List of Order objects. The constructor of Lazy<T> is passed a lambda expression that expresses what needs to be returned when the list of orders is requested for (our expensive logic). Notice I’ve also put a call to Debug.WriteLine so you can observe the output of the following code and see how this behaves.

var customer = new Customer(1);
                       
Debug.WriteLine("Are orders instantiated? {0}", 
    customer.Orders.IsValueCreated);

// Ok, we now want the orders...
var ordersForCustomer = customer.Orders.Value;

Debug.WriteLine("Are orders instantiated? {0}", 
    customer.Orders.IsValueCreated);

Debug.WriteLine("Customer {0} has {1} order(s)", 
    customer.Id, ordersForCustomer.Count);

If you execute the code above using the updated Customer class, you’ll find that instantiating a Customer object is no longer an expensive operation. The output you should see in your debug window is:

I'm customer with id 1
Are orders instantiated? False
Are orders instantiated? True
Customer 1 has 200 order(s)

Notice that when the Customer object was initialised, the runtime executed the constructor logic as expected (verifiable with the ToString output). We then check our Lazy objects IsValueCreated property to ensure it hasn’t yet created an instance of the list and populated it. The property returned False as expected. On the next line, we explicitly call the Value property on the Orders property (our Lazy object) – this forces our lazy object to instantiate. We re-query the IsValueCreated property which now returns True and finally we output the order count to show that the orders have been successfully lazily-loaded.

C# MongoDB Repository Implementation

I recently started a small project with a friend and we opted for MongoDB as our data store. One of the initial tasks was to write a repository class that allowed us to store, retrieve, update and search for entities in MongoDB. In the past, I’ve worked on codebases where there was one repository per entity, it didn’t take long to discover that this resulted in a lot of code duplication across the data layer. So the goal here was to write the repository generically enough so that we only have one implementation that can be reused for any entity within our application. This meant that each entity would have its own MongoDB collection (if you’re not familiar with MongoDB, a collection can be thought of as a table in the relational world – see this page for a comparison).

One of the first steps in this task was to write an interface for the repository – this is in case we decide to use a different data store in the future. A while back, I found a repository interface on the Redmondo blog which covers everything I’d want from a repository, so we’ll use a slightly modified version of that interface (I’ve removed comments for brevity, you can download the code using a link further below and that’ll contain the comments):

public interface IRepository<TEntity> where TEntity : EntityBase
{
bool Insert(TEntity entity);
bool Update(TEntity entity);
bool Delete(TEntity entity);
IList<TEntity>
SearchFor(Expression<Func<TEntity, bool>> predicate);
IList<TEntity> GetAll();
TEntity GetById(Guid id);
}

To paraphrase the code, this is a generic repository interface for an entity of type TEntity that must derive from a base class called EntityBase. The EntityBase class is a very simple abstract class and contains just one property, the identifier property:

/// <summary>
/// A non-instantiable base entity which defines 
/// members available across all entities.
/// </summary>
public abstract class EntityBase
{
public Guid Id { get; set; }
}

The idea is for any entity that we want to manage in our data store, that entity must derive from EntityBase. So the infrastructure is all in place for our “MongoDbRepository”. I used the official 10gen MongoDB C# driver (available as a NuGet package) and arrived at the following repository implementation:

/// <summary>
/// A MongoDB repository. Maps to a collection with the same name
/// as type TEntity.
/// </summary>
/// <typeparam name=”T”>Entity type for this repository</typeparam>
public class MongoDbRepository<TEntity> :
IRepository<TEntity> where
TEntity : EntityBase
{
private MongoDatabase database;
private MongoCollection<TEntity> collection;

public MongoDbRepository()
{
GetDatabase();
GetCollection();
}

public bool Insert(TEntity entity)
{
entity.Id = Guid.NewGuid();
return collection.Insert(entity).Ok;
}

public bool Update(TEntity entity)
{
if (entity.Id == null)
return Insert(entity);

return collection
.Save(entity)
.DocumentsAffected > 0;
}

public bool Delete(TEntity entity)
{
return collection
.Remove(Query.EQ(“_id”, entity.Id))
.DocumentsAffected > 0;
}

public IList<TEntity>
SearchFor(Expression<Func<TEntity, bool>> predicate)
{
return collection
.AsQueryable<TEntity>()
.Where(predicate.Compile())
.ToList();
}

public IList<TEntity> GetAll()
{
return collection.FindAllAs<TEntity>().ToList();
}

public TEntity GetById(Guid id)
{
return collection.FindOneByIdAs<TEntity>(id);
}

#region Private Helper Methods
private void GetDatabase()
{
var client = new MongoClient(GetConnectionString());
var server = client.GetServer();

database = server.GetDatabase(GetDatabaseName());
}

private string GetConnectionString()
{
return ConfigurationManager
.AppSettings
.Get(“MongoDbConnectionString”)
.Replace(“{DB_NAME}”, GetDatabaseName());
}

private string GetDatabaseName()
{
return ConfigurationManager
.AppSettings
.Get(“MongoDbDatabaseName”);
}

private void GetCollection()
{
collection = database
.GetCollection<TEntity>(typeof(TEntity).Name);
}
#endregion
}

In case you’re interested, a while ago I wrote a separate blog post on how to perform CRUD operations against MongoDB using the C# driver. To use the repository implementation, you’ll need two application configuration settings defined – one that stores the name of the MongoDB database and the other that contains the MongoDB connection string (with a placeholder for the database name). You should have something like:

<appSettings>
<add key=“MongoDbDatabaseName” value=“MyCarsDatabase” />
<add key=“MongoDbConnectionString”
value=“mongodb://localhost/{DB_NAME}?safe=true” />
</appSettings>

 

CSharp – ExpandoObject Stringified

I had a requirement to output some data as part of a number of pages in an e-commerce site. This data would change from page to page and typically get richer as a user would go through an order path in the application. The data needed to be in JSON format and was going to be used by the marketing guys to help track information about user behaviour across the order process. The data was also subject to change regularly depending on what the marketing team wanted to track. In short, I had to construct a JSON string on the server side in C#.

I had seen something like this done before where a StringBuilder was used to construct a large JSON string which was then pushed out in the response with the rest of the page markup. This approach seemed messy and difficult to maintain. I did a bit of research on some approaches to constructing a potentially complex and changing JSON object using C# and came across the ExpandoObject class. MSDN has a nice succinct explanation of ExpandoObject:

Represents an object whose members can be dynamically added and removed at run time.

You can find this class in .NET 4 in the System.Dynamic namespace. ExpandoObject lets you effectively “model” an object on the fly with properties that don’t really exist (just like using the ViewBag in ASP.NET MVC). In my case, it saved me from writing a number of classes or complex strings just to hold data that was to be output in page responses. Instead, I could use ExpandoObject and then use a JSON serializer to stringify the object.

The example below shows how easy and flexible it is to use ExpandoObject with the Newtonsoft .NET JSON library (available as a NuGet package):

dynamic orderInfo = new ExpandoObject();

orderInfo.OrderDate = DateTime.Today;

orderInfo.ProductTypesAdded = new List<dynamic>();
orderInfo.ProductTypesAdded.Add(“Radio”);
orderInfo.ProductTypesAdded.Add(“Television”);
orderInfo.ProductTypesAdded.Add(“Recorder”);

orderInfo.ReachedCheckout = true;
orderInfo.PaymentMethod = “Card”;

orderInfo.DeliveryInfo = new ExpandoObject();
orderInfo.DeliveryInfo.Method = “First”;
orderInfo.DeliveryInfo.Country = “UK”;

var json = JsonConvert.SerializeObject(orderInfo);

The resulting JSON is:

{
“OrderDate”:”2013-10-11T00:00:00+01:00″,
“ProductTypesAdded”:[
“Radio”,
“Television”,
“Recorder”
],
“ReachedCheckout”:true,
“PaymentMethod”:”Card”,
“DeliveryInfo”:{
“Method”:”First”,
“Country”:”UK”
}
}