Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Caching is Key</strong></p> <p>As the others have said, you've got to use caching since you are performing repetitive disk I/O on data that doesn't change often.</p> <p>My example creates and caches a <code>List&lt;T&gt;</code> of the image file paths you will need for each subsequent request. <code>System.Web.Caching</code> is perfect for this because you can create a <code>CacheDependency</code> object directly on your image directory -- if a file gets changed or added, your cache is automatically invalidated. It is then recreated the next time it is requested.</p> <p><strong>Avoiding Duplicates with the <code>HashSet&lt;T&gt;</code></strong></p> <p>I bet you don't want two of the same pictures ever showing up in your header!</p> <p>Randomizing using <code>Random.Next</code> does not exclude previously generated duplicates. I used a <code>HashSet&lt;T&gt;</code> as a poor man's unique randomizer since the <code>HashSet&lt;T&gt;</code> will only allow you to add unique values.</p> <p><strong>The Model</strong></p> <p>This operation should be part of your model in MVC. You change it to go along with your other data fetching classes as you see fit.</p> <pre><code>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Caching; public class RandomImage { public static string[] GetImages(string folder, int count) { HttpContext context = HttpContext.Current; string virtualFolderPath = string.Format("/content/{0}/", folder); string absoluteFolderPath = context.Server.MapPath(virtualFolderPath); Cache cache = context.Cache; var images = cache[folder + "_images"] as List&lt;string&gt;; // cache string array if it does not exist if (images == null) { var di = new DirectoryInfo(absoluteFolderPath); images = (from fi in di.GetFiles() where fi.Extension.ToLower() == ".jpg" || fi.Extension.ToLower() == ".gif" select string.Format("{0}{1}", virtualFolderPath, fi.Name)) .ToList(); // create cach dependency on image randomFolderName cache.Insert(folder + "_images", images, new CacheDependency(absoluteFolderPath)); } Random random = new Random(); var imageSet = new HashSet&lt;string&gt;(); if (count &gt; images.Count()) { throw new ArgumentOutOfRangeException("count"); } while (imageSet.Count() &lt; count) { //using an hashset will ensure a random set with unique values. imageSet.Add(images[random.Next(count)]); } return imageSet.ToArray(); } } </code></pre> <p><strong>The Controller</strong></p> <p>Access the method in your controller something like....</p> <pre><code>string[] images = Models.RandomImage.GetImages("myPictures", 4); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload