using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PMS.Plugins.Common
{
public static class HashtableHelper
{
private static Hashtable ht = Hashtable.Synchronized(new Hashtable());
private static object obj = new object();
///
/// 添加一个缓存项
///
/// 关键字 Key
/// 数据值
public static void AddCacheIitems(string key, object data)
{
try
{
if (key != "")
{
lock (ht.SyncRoot) //zxm20140212添加
{
if (ht[key] != null)
ht.Remove(key);
ht.Add(key, data);
}
}
}
catch (Exception)
{
}
}
///
/// 获取Hashtable键值
///
/// key
///
public static object GetCacheIitems(string key)
{
if (key != "")
{
lock (ht.SyncRoot)
{
return ht[key];
}
}
else
{
return null;
}
}
///
/// 移除Hashtable键值
///
/// key
public static void RemoveCacheItems(string key)
{
if (key != "")
{
lock (ht.SyncRoot)
{
ht.Remove(key);
}
}
}
///
/// 移除所有缓存值
///
public static void RemoveAllCacheItems()
{
lock (ht.SyncRoot)
{
ht.Clear();
}
}
public static string GetHashtableCount(string key)
{
string r = "【insureSys:" + ht[key];
return r + "|Hashtable键值总和:" + ht.Count + "】";
}
///
/// 批量移除缓存
///
///
public static void BatchRemoveCacheItems(string key)
{
lock (ht.SyncRoot)
{
foreach (DictionaryEntry h in ht)
{
string keyName = h.Key.ToStringEx();
if (keyName.Contains(key))
{
ht.Remove(keyName);
}
}
}
}
///
/// 将DataTable 转换hashTable
///
///
///
public static Hashtable DataTableToHashTable(DataTable dt)
{
DataRow row = dt.Rows[0];
Hashtable hash = new Hashtable();
for (int i = 0; i < row.Table.Columns.Count; i++)
{
if (row[row.Table.Columns[i].ColumnName].ToStringEx() != "")
hash.Add(row.Table.Columns[i].ColumnName, row[row.Table.Columns[i].ColumnName].ToStringEx());
}
return hash;
}
///
/// 获取一个6位验证码随机数
///
///
private static int NewRandom()
{
lock (obj)
{
Random r = new Random(System.Environment.TickCount);
int i = r.Next(100000, 999999);
return i;
}
}
///
/// 新生成一个Key
///
///
public static string NewKey()
{
string guid = NewRandom().ToStringEx();//Guid.NewGuid().ToString().ToUpper();
return guid;
}
}
}