public KeyValueList LoginCheck()
        {
            var results = new KeyValueList();
            // If context user exist then...
            string currentUser = string.Empty;

            if (System.Web.HttpContext.Current.User != null)
            {
                if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    currentUser = System.Web.HttpContext.Current.User.Identity.Name;
                }
            }
            results.Add("FormsCookieName", FormsAuthentication.FormsCookieName);
            //FormsAuthentication.GetAuthCookie();
            HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (cookie.Value.Length > 0)
            {
                var ticket = FormsAuthentication.Decrypt(cookie.Value);
            }

            string v = string.Empty;

            for (int i = 0; i < cookie.Values.AllKeys.Length; i++)
            {
                v += cookie.Values.AllKeys[i] + ", ";
            }
            results.Add("values", cookie.Value.ToString());
            //System.Web.HttpContext.Current.Response.Cookies;
            results.Add("IdentityName", System.Threading.Thread.CurrentPrincipal.Identity.Name);
            results.Add("CurrentUser", currentUser);
            return(results);
        }
        public void Collections_KeyValueList_GetValue()
        {
            var kvList = new KeyValueList <int, double>();

            kvList.Add(1, 100.00);
            kvList.Add(2, 200.00);
            Assert.IsTrue(kvList.GetValue(2) == 200.00);
        }
        public void Collections_KeyValueList_Remove()
        {
            var kvList = new KeyValueList <int, double>();

            kvList.Add(1, 100.00);
            kvList.Add(2, 200.00);
            kvList.Remove(1);
            Assert.IsTrue(kvList.Count == 1);
        }
示例#4
0
        public KeyValueList SignOut()
        {
            FormsAuthentication.SignOut();
            var results = new KeyValueList();

            results.Add("Status", true);
            results.Add("Message", "Good bye!");
            return(results);
        }
        public void Collections_KeyValueList_Add()
        {
            var kvList = new KeyValueList <int, int>();

            kvList.Add(new KeyValuePairSafe <int, int>(0, 0));
            kvList.Add(new KeyValuePairSafe <int, int>(1, 1));
            kvList.Add(new KeyValuePairSafe <int, int>(2, 2));

            Assert.AreNotEqual(2, kvList.Count);
            Assert.AreEqual(3, kvList.Count);
        }
        public void Collections_KeyValueList_ToString()
        {
            var kvList          = new KeyValueList <int, StringMutable>();
            var delimiterLength = 0;
            var lengthExpected  = 0;

            kvList.Add(1, "Value1");
            kvList.Add(2, "Value2");
            kvList.Add(3, "Value3");
            foreach (var item in kvList)
            {
                lengthExpected += item.ToString().Length + delimiterLength;
                delimiterLength = 2;
            }
            Assert.IsTrue(kvList.ToString("G").Length == lengthExpected);
        }
示例#7
0
        public TerritoryIDType?MoveTowardsNearestBorder(TerritoryIDType id, bool neutralOk)
        {
            var neighborDistances = new KeyValueList <TerritoryIDType, int>();

            foreach (var immediateNeighbor in Map.Territories[id].ConnectedTo.Keys)
            {
                var nearestBorder = FindNearestBorder(immediateNeighbor, id, neutralOk);
                if (nearestBorder != null)
                {
                    neighborDistances.Add(immediateNeighbor, nearestBorder.Depth);
                }
            }

            if (neighborDistances.Count == 0)
            {
                return(null);
            }

            var ret      = neighborDistances.GetKey(0);
            int minValue = neighborDistances.GetValue(0);

            for (int i = 1; i < neighborDistances.Count; i++)
            {
                if (neighborDistances.GetValue(i) < minValue)
                {
                    ret      = neighborDistances.GetKey(i);
                    minValue = neighborDistances.GetValue(i);
                }
            }

            return(ret);
        }
示例#8
0
        protected override KeyValueList <Grouping, IEnumerable <ParsedData> > GroupFields(IEnumerable <ParsedData> data)
        {
            var res = new KeyValueList <Grouping, IEnumerable <ParsedData> >();

            Grouping currentGroup = null;
            var      currentLogs  = new List <ParsedData>();

            foreach (var log in data.ToList().OrderBy(d => d.Log.Date))
            {
                if (currentGroup == null)
                {
                    currentGroup = new Grouping(Boss.GetByID(log.Log.BossID).Area);
                }

                if (!currentGroup.Equals(Boss.GetByID(log.Log.BossID).Area))
                {
                    if (currentLogs.Count > 0)
                    {
                        currentGroup = GetGrouping(currentLogs);
                        if (currentLogs.All(l => l.Log.IsCM))
                        {
                            currentGroup.PostFix = "CM";
                        }
                        res.Add(currentGroup, currentLogs);
                    }
                    currentGroup = new Grouping(Boss.GetByID(log.Log.BossID).Area);
                    currentLogs  = new List <ParsedData>();
                }

                currentLogs.Add(log);
            }

            if (currentGroup == null)
            {
                return(res);
            }

            currentGroup = GetGrouping(currentLogs);
            if (currentLogs.All(l => l.Log.IsCM))
            {
                currentGroup.PostFix = "CM";
            }
            res.Add(currentGroup, currentLogs);

            return(res);
        }
        public KeyValueList LoginRestore()
        {
            System.Web.Security.FormsAuthentication.SignOut();
            System.Web.Security.FormsAuthentication.RedirectToLoginPage();
            var results = new KeyValueList();

            results.Add("Status", true);
            return(results);
        }
示例#10
0
    public static async Task SendAuthenticateHeaderAsync(HttpResponse response, string realm, CancellationToken cancel = default)
    {
        KeyValueList <string, string> basicAuthResponseHeaders = new KeyValueList <string, string>();

        basicAuthResponseHeaders.Add(Consts.HttpHeaders.WWWAuthenticate, $"Basic realm=\"{realm}\"");

        await using var basicAuthRequireResult = new HttpStringResult("Basic Auth Required", contentType: Consts.MimeTypes.TextUtf8, statusCode: Consts.HttpStatusCodes.Unauthorized, additionalHeaders: basicAuthResponseHeaders);

        await response._SendHttpResultAsync(basicAuthRequireResult, cancel : cancel);
    }
    protected override async Task GetValueAsync(SortedDictionary <string, string> ret, RefInt nextPollingInterval, CancellationToken cancel = default)
    {
        var result = await EasyExec.ExecAsync(Consts.LinuxCommands.Free, "-b -w");

        string[] lines = result.OutputStr._GetLines();

        List <string> headers = new List <string>();

        KeyValueList <string, string> dataList = new KeyValueList <string, string>();

        foreach (string line in lines)
        {
            string[] tokens = line._Split(StringSplitOptions.RemoveEmptyEntries, ' ', '\t');

            if (tokens.Length >= 2)
            {
                if (headers.Count == 0)
                {
                    if (tokens[0]._IsSamei("total"))
                    {
                        // ヘッダ行
                        foreach (string token in tokens)
                        {
                            headers.Add(token);
                        }
                    }
                }
                else
                {
                    // データ行
                    if (tokens[0]._IsSamei("Mem:"))
                    {
                        for (int i = 1; i < tokens.Length; i++)
                        {
                            if (headers.Count >= (i - 1))
                            {
                                dataList.Add(headers[i - 1], tokens[i]);
                            }
                        }
                    }
                }
            }
        }

        // total
        long total     = dataList._GetStrFirst("total", "-1")._ToLong();
        long available = dataList._GetStrFirst("available", "-1")._ToLong();

        if (total >= 0 && available >= 0)
        {
            available = Math.Min(available, total);
            ret.TryAdd($"available", NormalizeDoubleValue(((double)available * 100.0 / (double)total).ToString("F3")));
        }
    }
        public KeyValueList Logout()
        {
            //// Abandon ASP Session first.
            //JocysCom.WebSites.WebApp.ServerVariables.Exchanger exchanger;
            //exchanger = new JocysCom.WebSites.WebApp.ServerVariables.Exchanger();
            //exchanger.AbandonAspSession();
            // Abandon ASPX Session.
            System.Web.Security.FormsAuthentication.SignOut();
            Session.Abandon();
            var results = new KeyValueList();

            results.Add("Status", true);
            return(results);
        }
示例#13
0
        static int MergeResourceHeader(ConsoleService c, string cmdName, string str)
        {
            string baseFile   = @"C:\git\IPA-DNP-DeskVPN\src\PenCore\resource.h";
            string targetFile = @"C:\sec\Desk\current\Desk\DeskVPN\PenCore\resource.h";
            string destFile   = @"c:\tmp\200404\resource.h";
            int    minId      = 2500;

            var baseDict   = DevTools.ParseHeaderConstants(Lfs.ReadStringFromFile(baseFile));
            var targetDict = DevTools.ParseHeaderConstants(Lfs.ReadStringFromFile(targetFile));

            KeyValueList <string, int> adding = new KeyValueList <string, int>();

            // 利用可能な ID の最小値
            int newId = Math.Max(baseDict.Values.Where(x => x < 40000).Max(), minId);

            foreach (var kv in targetDict.OrderBy(x => x.Value))
            {
                if (baseDict.ContainsKey(kv.Key) == false)
                {
                    adding.Add(kv.Key, ++newId);
                }
            }

            // 結果を出力
            StringWriter w = new StringWriter();

            foreach (var kv in adding)
            {
                int paddingCount = Math.Max(31 - kv.Key.Length, 0);

                w.WriteLine($"#define {kv.Key}{Str.MakeCharArray(' ', paddingCount)} {kv.Value}");
            }

            Lfs.WriteStringToFile(destFile, w.ToString(), FileFlags.AutoCreateDirectory);

            return(0);
        }
    protected override void InitImpl(object?param = null)
    {
        // sensors コマンドが利用可能かどうか確認
        if (EasyExec.ExecAsync(Consts.LinuxCommands.Sensors, "-u")._TryGetResult() != default)
        {
            IsSensorsCommandOk = true;
        }

        // /sys/class/thermal/ から取得可能な値一覧を列挙
        FileSystemEntity[]? dirList = null;
        try
        {
            dirList = Lfs.EnumDirectory(Consts.LinuxPaths.SysThermal);
        }
        catch { }

        if (dirList != null)
        {
            foreach (var dir in dirList)
            {
                string fileName = Lfs.PathParser.Combine(dir.FullPath, "temp");

                if (Lfs.IsFileExists(fileName))
                {
                    try
                    {
                        Lfs.ReadStringFromFile(fileName);

                        ThermalFiles.Add(dir.Name, fileName);
                    }
                    catch
                    {
                    }
                }
            }
        }
    }
示例#15
0
        public KeyValueList SignIn(string username, string password)
        {
            string errorMessage = string.Empty;

            if (password.Length == 0)
            {
                errorMessage = "Please enter password";
            }
            if (username.Length == 0)
            {
                errorMessage = "Please enter user name";
            }
            if (errorMessage.Length == 0)
            {
                // Here must be validation with password. You can add third party validation here;
                bool success = Membership.ValidateUser(username, password);
                if (!success)
                {
                    errorMessage = "Validation failed. User name '" + username + "' was not found.";
                }
            }
            var results = new KeyValueList();

            if (errorMessage.Length > 0)
            {
                results.Add("Status", false);
                results.Add("Message", errorMessage);
            }
            else
            {
                FormsAuthentication.Initialize();
                var user = Membership.GetUser(username, true);
                if (user == null)
                {
                    results.Add("Status", false);
                    results.Add("Message", "'" + username + "' was not found.");
                }
                else
                {
                    var    roles       = Roles.GetRolesForUser(username);
                    string rolesString = string.Empty;
                    for (int i = 0; i < roles.Length; i++)
                    {
                        if (i > 0)
                        {
                            rolesString += ",";
                        }
                        rolesString += roles[i];
                    }
                    var loginRememberMinutes = 30;
                    var ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(loginRememberMinutes), true, rolesString, FormsAuthentication.FormsCookiePath);
                    // Encrypt the cookie using the machine key for secure transport.
                    var hash   = FormsAuthentication.Encrypt(ticket);
                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);                     // Hashed ticket
                    // Set the cookie's expiration time to the tickets expiration time
                    if (ticket.IsPersistent)
                    {
                        cookie.Expires = ticket.Expiration;
                    }
                    HttpContext.Current.Response.Cookies.Add(cookie);
                    // Create Identity.
                    var identity = new System.Security.Principal.GenericIdentity(user.UserName);
                    // Create Principal.
                    var principal = new RolePrincipal(identity);
                    System.Threading.Thread.CurrentPrincipal = principal;
                    // Create User.
                    HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
                    results.Add("Status", true);
                    results.Add("Message", "Welcome!");
                }
            }
            return(results);
        }
示例#16
0
    public string GetSnmpBody(SnmpWorkGetMethod method, string requestedOid, bool returnNone)
    {
        string nullReturnStr = returnNone ? "NONE" : "";

        SortedDictionary <string, KeyValuePair <string, int> > values = GetValues();

        KeyValueList <int, string> namesList  = new KeyValueList <int, string>();
        KeyValueList <int, string> valuesList = new KeyValueList <int, string>();

        // index 順にソート
        foreach (var kv in values.OrderBy(x => x.Value.Value))
        {
            int    index = kv.Value.Value;
            string name  = kv.Key;
            string value = kv.Value.Key;

            namesList.Add(index, name);
            valuesList.Add(index, value);
        }

        KeyValueList <int, string>?list = null;

        int specifiedIndex = -1;

        string oidPrefix = "";

        if (requestedOid.StartsWith(Consts.SnmpOids.SnmpWorkNames))
        {
            list = namesList;
            string remain = requestedOid.Substring(Consts.SnmpOids.SnmpWorkNames.Length);
            specifiedIndex = 0;
            if (remain.StartsWith("."))
            {
                specifiedIndex = remain.Substring(1)._ToInt();
            }
            oidPrefix = Consts.SnmpOids.SnmpWorkNames;
        }
        else if (requestedOid.StartsWith(Consts.SnmpOids.SnmpWorkValues))
        {
            list = valuesList;
            string remain = requestedOid.Substring(Consts.SnmpOids.SnmpWorkValues.Length);
            specifiedIndex = 0;
            if (remain.StartsWith("."))
            {
                specifiedIndex = remain.Substring(1)._ToInt();
            }
            oidPrefix = Consts.SnmpOids.SnmpWorkValues;
        }

        if (method == SnmpWorkGetMethod.GetAll)
        {
            // すべてのオブジェクトを列挙する
            StringWriter w = new StringWriter();
            for (int i = 0; i < namesList.Count; i++)
            {
                w.WriteLine($"{namesList[i].Value} ({namesList[i].Key}): {valuesList[i].Value}");
            }
            return(w.ToString());
        }

        if (specifiedIndex < 0 || list == null)
        {
            // 不正
            return(nullReturnStr);
        }

        if (method == SnmpWorkGetMethod.GetNext)
        {
            // 指定された index よりも 1 つ次のオブジェクトを返す
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Key > specifiedIndex)
                {
                    //                        return oidPrefix + "." + list[i].Key + "\nobjectid\n" + oidPrefix + "." + list[i].Key;
                    return(oidPrefix + "." + list[i].Key + "\nstring\n" + list[i].Value._FilledOrDefault("-"));
                }
            }

            return(nullReturnStr);
        }
        else
        {
            // 指定された index のオブジェクトを返す
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Key == specifiedIndex)
                {
                    return(oidPrefix + "." + list[i].Key + "\nstring\n" + list[i].Value._FilledOrDefault("-"));
                }
            }

            return(nullReturnStr);
        }
    }
示例#17
0
    async Task PostHttpMainAsync(CancellationToken cancel = default)
    {
        if (this.Config.PostUrl._IsEmpty())
        {
            return;
        }

        StatManDatabase copy;

        lock (this.DataLock)
        {
            copy = this.Database._CloneWithJson();
        }

        KeyValueList <string, string> vers = new KeyValueList <string, string>();

        vers.Add("APPNAME", CoresLib.AppNameFnSafe);
        vers.Add("OS", Env.OsInfoString);
        vers.Add("CPU", Env.CpuInfo.ToString());
        vers.Add("NUMCPU", Env.NumCpus.ToString());
        vers.Add("DOTNET", Env.FrameworkInfoString);
        vers.Add("EXE", Env.AppExecutableExeOrDllFileName._GetFileName() ?? "");

        List <string> versStrs = new List <string>();

        vers.ForEach(x => versStrs.Add($"{x.Key}={x.Value}"));

        var data = Json.NewJsonObject();

        foreach (var item in copy.StrValues)
        {
            data.TryAdd(item.Key, new JValue(item.Value));
        }

        foreach (var item in copy.LongValues)
        {
            data.TryAdd(item.Key, new JValue(item.Value));
        }

        DataVaultData postData = new DataVaultData
        {
            TimeStamp       = DtOffsetNow,
            StatUid         = copy.Uid,
            StatAppVer      = versStrs._Combine("|"),
            StatGitCommitId = Dbg.GetCurrentGitCommitId(),
            StatLocalIp     = this.CurrentLocalIp.ToString(),
            StatLocalFqdn   = LocalNet.GetHostInfo(true).HostName,
            SystemName      = Config.SystemName,
            LogName         = Config.LogName,
            Data            = data,
        };

        string postStr = postData._ObjectToJson();

        using var http = new WebApi(new WebApiOptions(new WebApiSettings { SslAcceptAnyCerts = true }));

        var ret = await http.SimplePostJsonAsync(WebMethods.POST, Config.PostUrl, postStr, cancel);

        if (ret.ToString()._InStr("ok") == false)
        {
            throw new CoresException($"Http error: {ret.ToString()._TruncStrEx(1000)}");
        }
    }
示例#18
0
 public KeyValueList SignOut()
 {
     FormsAuthentication.SignOut();
     var results = new KeyValueList();
     results.Add("Status", true);
     results.Add("Message", "Good bye!");
     return results;
 }
示例#19
0
        public IActionResult Index()
        {
            KeyValueList <string, string> o = new KeyValueList <string, string>();

            string msg = "Hello 35!";

            o.Add("メッセージ", msg);

            o.Add("メッセージ 2", Dbg.HelloMsgTest);

            o.Add("起動時刻", Env.BootTime.ToLocalTime()._ToDtStr());

            o.Add("Git Commit Id", Dbg.GetCurrentGitCommitId());

            o.Add("Git Comment", Dbg.GetCurrentGitCommitInfo()?.Description ?? "-");

            o.Add("Startup Arguments", GlobalDaemonStateManager.StartupArguments);

            o.Add("Process Id", Env.ProcessId.ToString());

            o.Add("BuildConfigurationName", Env.BuildConfigurationName);

            o.Add("ExeOrDllName", Env.AppExecutableExeOrDllFileName);

            o.Add("RealExeName", Env.AppRealProcessExeFileName);

            o.Add("IsDotNetCore", Env.IsDotNetCore.ToString());

            o.Add(".NET Version", Env.FrameworkInfoString);

            o.Add("DotNetHostProcessExeName", Env.DotNetHostProcessExeName);

            o.Add("AppRootDir", Env.AppRootDir);

            o.Add("GC Mode", Env.GcMode);

            // 環境変数
            StringWriter w   = new StringWriter();
            var          dic = Environment.GetEnvironmentVariables();
            KeyValueList <string, string> tmp = new KeyValueList <string, string>();

            foreach (System.Collections.DictionaryEntry?kv in dic)
            {
                if (kv?.Key is string key2)
                {
                    if (kv?.Value is string value2)
                    {
                        tmp.Add(key2._NonNullTrim(), value2._NonNullTrim());
                    }
                }
            }

            tmp.OrderBy(x => x.Key)._DoForEach(x => w.WriteLine($"{x.Key} = {x.Value}"));

            o.Add("Environment Values", w.ToString());

            //string a = Str.MakeCharArray('x', 100_000);
            // テスト

/*            for (int i = 0;; i++)
 *          {
 *              i._PostData();
 *          } */

            return(View(o));
        }
示例#20
0
 public KeyValueList SignIn(string username, string password)
 {
     string errorMessage = string.Empty;
     if (password.Length == 0) errorMessage = "Please enter password";
     if (username.Length == 0) errorMessage = "Please enter user name";
     if (errorMessage.Length == 0)
     {
         // Here must be validation with password. You can add third party validation here;
         bool success = Membership.ValidateUser(username, password);
         if (!success) errorMessage = "Validation failed. User name '" + username + "' was not found.";
     }
     var results = new KeyValueList();
     if (errorMessage.Length > 0)
     {
         results.Add("Status", false);
         results.Add("Message", errorMessage);
     }
     else
     {
         FormsAuthentication.Initialize();
         var user = Membership.GetUser(username, true);
         if (user == null)
         {
             results.Add("Status", false);
             results.Add("Message", "'" + username + "' was not found.");
         }
         else
         {
             var roles = Roles.GetRolesForUser(username);
             string rolesString = string.Empty;
             for (int i = 0; i < roles.Length; i++)
             {
                 if (i > 0) rolesString += ",";
                 rolesString += roles[i];
             }
             var loginRememberMinutes = 30;
             var ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(loginRememberMinutes), true, rolesString, FormsAuthentication.FormsCookiePath);
             // Encrypt the cookie using the machine key for secure transport.
             var hash = FormsAuthentication.Encrypt(ticket);
             var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); // Hashed ticket
             // Set the cookie's expiration time to the tickets expiration time
             if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
             HttpContext.Current.Response.Cookies.Add(cookie);
             // Create Identity.
             var identity = new System.Security.Principal.GenericIdentity(user.UserName);
             // Create Principal.
             var principal = new RolePrincipal(identity);
             System.Threading.Thread.CurrentPrincipal = principal;
             // Create User.
             HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(identity, roles);
             results.Add("Status", true);
             results.Add("Message", "Welcome!");
         }
     }
     return results;
 }
    protected override async Task GetValueAsync(SortedDictionary <string, string> ret, RefInt nextPollingInterval, CancellationToken cancel = default)
    {
        SnmpWorkSettings settings = Host.Settings;

        if (settings.PingTargets._IsSamei("none") || settings.PingTargets._IsSamei("null"))
        {
            return;
        }

        string[] pingTargets = settings.PingTargets._Split(StringSplitOptions.RemoveEmptyEntries, ",");

        KeyValueList <string, IPAddress> kvList = new KeyValueList <string, IPAddress>();

        // 名前解決
        foreach (string pingTarget in pingTargets)
        {
            cancel.ThrowIfCancellationRequested();

            try
            {
                ParseTargetString(pingTarget, out string hostname, out string alias);

                IPAddress ip = await LocalNet.GetIpAsync(hostname, cancel : cancel);

                kvList.Add(alias, ip);
            }
            catch (Exception ex)
            {
                ex._Debug();
            }
        }

        List <Task <double> > taskList = new List <Task <double> >();

        int interval = 0;
        int count    = 3;

        // SpeedTest が動作中の場合は SpeedTest が完了するまで待機する
        numPerform++;
        if (numPerform >= 2)
        {
            interval = settings.PktLossIntervalMsec;
            count    = settings.PktLossTryCount;

            await TaskUtil.AwaitWithPollAsync(Timeout.Infinite, 10, () => !SpeedTestClient.IsInProgress, cancel);
        }

        // 並列実行の開始
        foreach (var kv in kvList)
        {
            taskList.Add(PerformOneAsync(kv.Value, count, settings.PktLossTimeoutMsecs, interval, cancel));
        }

        // すべて終了するまで待機し、結果を整理
        for (int i = 0; i < kvList.Count; i++)
        {
            var kv   = kvList[i];
            var task = taskList[i];

            double lossRate = await task._TryAwait();

            double quality = 1.0 - lossRate;

            quality = Math.Max(quality, 0.0);
            quality = Math.Min(quality, 1.0);

            ret.TryAdd($"{kv.Key}", ((double)quality * 100.0).ToString("F3"));
        }
    }