using Npgsql; using System; using System.Collections.Generic; using System.Configuration; using System.Data.Common; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security.AccessControl; using System.Security.Principal; using System.Web; namespace ExportMap.cs { public class Tool { public static readonly string BaseDir = AppDomain.CurrentDomain.BaseDirectory; public static string FormatBytes(long bytes) { string[] Suffix = { "Byte", "KB", "MB", "GB", "TB" }; int i = 0; double dblSByte = bytes; if (bytes > 1024) for (i = 0; (bytes / 1024) > 0; i++, bytes /= 1024) dblSByte = bytes / 1024.0; return String.Format("{0:0.##}{1}", dblSByte, Suffix[i]); } public static string GetSetting(string key) { return ConfigurationManager.AppSettings[key]; } public static List GetParams(string sql, T t) { List list = new List(); Type tType = typeof(T); BindingFlags flags = BindingFlags.Public | BindingFlags.IgnoreCase | BindingFlags.Instance; int start = sql.IndexOf("@"); while (start != -1) { int end = sql.IndexOf(",", start); if (end == -1) end = sql.IndexOf(")", start); if (end == -1) end = sql.IndexOf(" ", start); if (end == -1) end = sql.Length; string name = sql.Substring(start + 1, end - start - 1); PropertyInfo pi = tType.GetProperty(name, flags); if (pi != null) { object value = pi.GetValue(t, null); DbParameter dp = new NpgsqlParameter("@" + name, value); list.Add(dp); } start = sql.IndexOf("@", end); } return list; } public static void CreateDirectory(string dir) { WindowsIdentity wi = WindowsIdentity.GetCurrent(); FileSystemAccessRule rule = new FileSystemAccessRule(wi.User, FileSystemRights.FullControl, AccessControlType.Allow); DirectorySecurity ds = new DirectorySecurity(); ds.AddAccessRule(rule); Directory.CreateDirectory(dir, ds); } public static T Clone(T source) where T : new() { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", "source"); } // Don't serialize a null object, simply return the default for that object if (Object.ReferenceEquals(source, null)) { return default(T); } using (Stream stream = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } } }