0

We try to hotfix an old ASP.NET project. only got PHP experience yet.

Instead of the below, the 'Key' needs to be randomly selected from a list so that each "key" is used about equally often.

string sKey = ConfigurationManager.AppSettings["Key"];

(Referring to the web.config file.)

For example 10000 people use the site per day, 20000 pageviews. now there are 20 keys* and each should be used for approximately 500 users** or for approximately 1000 pageviews**.

*(Currently in a static file, "keys.txt", one key per line)

**(users can only be distinguished by their IPv4s, but total random is ok too)

1 Answers1

0

You can do that by creating a random number withing the range of the number of keys and use the one that was randomly selected.

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web.UI.WebControls;
using System.Linq;

//list to hold the keys
List<string> keys = new List<string>();

//dummy data
keys = Enumerable.Range(1, 20).Select(i => "Key_" + i).ToList();

//or read the file from disk
string path = Server.MapPath("keys.txt");
if (File.Exists(path))
{
    keys = File.ReadAllLines(path).ToList();
}

//create a random number and select the key
Random rnd = new Random();
string key = keys[rnd.Next(0, keys.Count)];
VDWWD
  • 35,079
  • 22
  • 62
  • 79
  • Maybe you need `HttpContext.Current.Server`. And `using System.Linq;` – VDWWD Nov 11 '19 at 14:28
  • Added all the `using` you need. – VDWWD Nov 11 '19 at 14:34
  • The reference should be there by default in Visual Studio. But if not add a reference to it. https://learn.microsoft.com/en-us/visualstudio/ide/managing-references-in-a-project?view=vs-2019#:~:targetText=A%20reference%20is%20essentially%20an,Explorer%20and%20choose%20Add%20Reference. – VDWWD Nov 11 '19 at 14:42
  • thanks, 0 Projects in "Solution Explorer", hence editing web.config https://stackoverflow.com/a/37695330 – Improved Tube Nov 11 '19 at 15:55
  • back to CS0117: 'System.Array' does not contain a definition for 'ToList' https://stackoverflow.com/a/57272803 (also this, but i we dont need dummy data CS0117: 'System.Collections.Generic.IEnumerable' does not contain a definition for 'Select' – ) – Improved Tube Nov 11 '19 at 16:46
  • got it working through this https://stackoverflow.com/a/6904455 edited your answer. thanks! – Improved Tube Nov 11 '19 at 18:27