using System;
using System.Collections.Generic;
using System.Xml;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Runtime.Caching;
namespace JeroenSteeman
{
class BotChecker
{
string[] storedBots;
MyCache objCache = new MyCache();
public bool DoesBotExist(string User_Agent)
{
if (!objCache.MyCacheContains("bots"))
{
storedBots = GetStringArray(AppDomain.CurrentDomain.BaseDirectory + "BotList.xml");
List<String> lstFiles = new List<string>();
lstFiles.Add(AppDomain.CurrentDomain.BaseDirectory + "BotList.xml");
objCache.AddToMyCache("bots",storedBots,MyCachePriority.Default,lstFiles);
}
else
{
storedBots = (string[])objCache.GetMyCachedItem("bots");
}
foreach (string bot in storedBots)
{
if (User_Agent.Contains(bot))
{
return true;
}
}
return false;
}
public string[] GetStringArray(string path)
{
var doc = XDocument.Load(path);
// Select all bot entries
var services = from service in doc.Descendants("bot")
select (string)service.Value;
return services.ToArray();
}
}
public enum MyCachePriority
{
Default,
NotRemovable
}
public class MyCache
{
// Get a reference to default MemoryCache instance.
private static ObjectCache cache = MemoryCache.Default;
private CacheItemPolicy policy = null;
private CacheEntryRemovedCallback callback = null;
public void AddToMyCache(String CacheKeyName, Object CacheItem, MyCachePriority MyCacheItemPriority, List<String> FilePath)
{
policy = new CacheItemPolicy();
policy.Priority = (MyCacheItemPriority == MyCachePriority.Default) ? CacheItemPriority.Default : CacheItemPriority.NotRemovable;
policy.AbsoluteExpiration = DateTimeOffset.Now.AddDays(1);
policy.RemovedCallback = callback; // not implemented
policy.ChangeMonitors.Add(new HostFileChangeMonitor(FilePath));
// Add inside cache
cache.Set(CacheKeyName, CacheItem, policy);
}
public Object GetMyCachedItem(String CacheKeyName)
{
return cache[CacheKeyName] as Object;
}
public void RemoveMyCachedItem(String CacheKeyName)
{
if (cache.Contains(CacheKeyName))
{
cache.Remove(CacheKeyName);
}
}
public Boolean MyCacheContains(String CacheKeyName)
{
if (cache.Contains(CacheKeyName))
{
return true;
}
else
{
return false;
}
}
}
}