示例#1
0
    public string Read()
    {
        var err = Libs.ReadConfig(CONF_FILE, setterDict);

        if (err != null)
        {
            return(err);
        }

        WorkingDir   = Path.GetFullPath(WorkingDir);
        OutFileDir   = Path.GetFullPath(OutFileDir);
        LastLineFile = Path.Combine(OutFileDir, LAST_LINE_FILE);

        var suffixes = new string[] { "", ".exe", ".bat" };

        foreach (var suffix in suffixes)
        {
            if (suffix.Length > 0 && WorkerFileName.EndsWith(suffix))
            {
                continue;
            }

            var realName = Path.Combine(WorkingDir, WorkerFileName + suffix);
            if (File.Exists(realName))
            {
                WorkerFileName = realName;
                break;
            }
        }

        return(null);
    }
示例#2
0
 /// <summary>
 /// LoadContent will be called once per game and is the place to load
 /// all of your content.
 /// </summary>
 protected override void LoadContent()
 {
     // Create a new SpriteBatch, which can be used to draw textures.
     _spriteBatch       = new SpriteBatch(GraphicsDevice);
     Canvas.SpriteBatch = _spriteBatch;
     Libs.Load(Content);
 }
示例#3
0
    public static ServiceInfo GetEasyService(string nameOrIndex)
    {
        var infoList = GetEasyServices();

        if (int.TryParse(nameOrIndex, out int i))
        {
            if (i < 1 || i > infoList.Count)
            {
                Libs.Abort($"Index \"{i}\" out of boundary 1~\"{infoList.Count}\"");
            }

            return(infoList[i - 1]);
        }

        foreach (var info in infoList)
        {
            if (info.Sc.ServiceName == nameOrIndex)
            {
                return(info);
            }
        }

        Libs.Abort($"EasyService \"{nameOrIndex}\" not exists");
        return(null);
    }
示例#4
0
        /// <summary>
        /// Handle messaging with the server.
        /// </summary>
        /// <param name="o"></param>
        static void ConnectionListener()
        {
            NetworkStream stream = client.GetStream();

            byte[] buffer = new byte[client.ReceiveBufferSize];

            try
            {
                while (!exit)
                {
                    int bytesRead = stream.Read(buffer, 0, client.ReceiveBufferSize);

                    if (bytesRead == 0)
                    {
                        break;
                    }

                    Message message = Message.FromBytes(buffer);
                    Libs.DisplayMessage(message);
                }
            }
            catch (IOException e)
            {
                Libs.StatusMessage(e.Message, StatusType.FAILURE);
            }

            stream.Close();
            Libs.StatusMessage("Connection lost with the server.");
        }
示例#5
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = Libs.DEFAULT_COLOR;
            Console.WriteLine("CONSOLECHAT DEDICATED SERVER");

            commands = new Dictionary <string, Command>();
            commands.Add("exit", new Command(CommandExit));

            listener = new TcpListener(IPAddress.Any, Libs.PORT);
            listener.Start();
            Libs.StatusMessage("Server started.");

            inputThread = new Thread(InputHandler);
            inputThread.Start();

            int count = 0;

            try
            {
                while (!exit)
                {
                    TcpClient client = listener.AcceptTcpClient();
                    lock (_lock) clients.Add(count, client);
                    Libs.StatusMessage("New connection from " + ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());

                    Thread t = new Thread(ConnectionListener);
                    listeners.Add(count, t);
                    t.Start(count++);
                }
            }
            catch (SocketException e)
            {
            }
        }
示例#6
0
    public void WriteOutput(string data)
    {
        if (ManageMode)
        {
            Console.WriteLine(data);
            return;
        }

        if (OutFileDir == null)
        {
            return;
        }

        var outFile = Path.Combine(OutFileDir, $"{DateTime.Now:yyyy-MM-dd}.log");

        try
        {
            Libs.WriteLineToFile(outFile, data, true);
        }
        catch (Exception ex)
        {
            Error($"Failed to write Worker's output to `{outFile}`: {ex.Message}");
        }

        try
        {
            Libs.WriteLineToFile(LastLineFile, data, false);
        }
        catch (Exception e)
        {
            Error($"Failed to write Worker's output to `{LastLineFile}`: {e.Message}");
        }
    }
示例#7
0
        public JsonResult AJXSearchRecipients()
        {
            int storeID = Session[Constant.SessionStoreID] != null?int.Parse(Session[Constant.SessionStoreID].ToString()) : -1;

            string keyword    = Request.Form["SearchKeyword"].ToString().Length < 1 ? null : Request.Form["SearchKeyword"];
            int    searchType = Request.Form["SearchType"] != null?int.Parse(Request.Form["SearchType"]) : -1;

            var isActive = Request.Form["IsActive"] == "on";
            int pageSize = int.Parse(ConfigurationManager.AppSettings["PageSize"]);

            PagedList.IPagedList result = null;
            int ddlStore = -1;

            if (!String.IsNullOrEmpty(Request.Form["ddlStore"]) && !Libs.IsStore())
            {
                ddlStore = Request.Form["ddlStore"] != null?int.Parse(Request.Form["ddlStore"]) : -1;
            }
            if (Libs.IsStore())
            {
                ddlStore = storeID;
            }
            if (Libs.IsAdmin())
            {
                result = _storeService.GetListRecieverByStoreID(1, pageSize, ddlStore, keyword, searchType, isActive);
            }
            else
            {
                result = _storeService.GetListRecieverByStoreID(1, pageSize, ddlStore, keyword, searchType, isActive);
            }
            return(Json(RenderPartialViewToString("_RecieverGrid", result), JsonRequestBehavior.AllowGet));
        }
示例#8
0
文件: Builder.cs 项目: vebin/XScript
        /// <summary>检查指定目录下是否有同名静态库</summary>
        /// <param name="di"></param>
        /// <param name="root"></param>
        /// <returns></returns>
        private Boolean CheckPartial(DirectoryInfo di, String root)
        {
            var fi = di.GetAllFiles("*.lib;*.a").FirstOrDefault();

            if (fi != null && fi.Exists)
            {
                if (!Libs.Contains(fi.FullName))
                {
                    var lib = new LibFile(fi.FullName);
                    WriteLog("发现静态库:{0, -12} {1}".F(lib.Name, fi.FullName));
                    Libs.Add(fi.FullName);
                }
                return(true);
            }

            var p = di.Parent;

            if (p == null || p == di)
            {
                return(false);
            }
            // 截止到当前目录
            if (p.FullName.EnsureEnd("\\").EqualIgnoreCase(root.GetFullPath().EnsureEnd("\\")))
            {
                return(false);
            }

            return(CheckPartial(p, root));
        }
示例#9
0
    private static void loggingSvc()
    {
        long prev = 0;

        while (true)
        {
            Thread.Sleep(200);

            var lastWrite = Libs.LastWriteTime(Conf.LastLineFile);

            if (lastWrite == 0 || lastWrite == prev)
            {
                continue;
            }

            try
            {
                using (var sr = new StreamReader(Conf.LastLineFile))
                {
                    Console.Write(sr.ReadToEnd());
                }
            }
            catch (Exception)
            {
                continue;
            }

            Console.Out.Flush();
            prev = lastWrite;
        }
    }
示例#10
0
        public override void LoadCurrent(Project prj)
        {
            var p = ManagedProject = prj as DProject;

            if (p == null)
            {
                return;
            }

            if (p.DMDVersion == DVersion.D1)
            {
                Combo_DVersion.SelectedIndex = 0;
            }
            else
            {
                Combo_DVersion.SelectedIndex = 1;
            }

            Check_Release.IsChecked = p.IsRelease;

            Libs.Clear();
            foreach (var l in p.LinkedLibraries)
            {
                Libs.Add(l);
            }

            if (Libs.Count > 0)
            {
                List_Libs.SelectedIndex = 0;
            }

            comboBox_PrjType.SelectedIndex = (int)p.OutputType;
        }
示例#11
0
    public Conf(Action <string> abort = null)
    {
        var setterDict = new Dictionary <string, Func <string, string> >
        {
            { "setServiceName", SetServiceName },
            { "setDisplayName", SetDisplayName },
            { "setDescription", SetDescription },
            { "setDependencies", SetDependencies },
            { "setWorker", SetWorker },
            { "setEnvironments", SetEnvironments },
            { "setWorkingDir", SetWorkingDir },
            { "setOutFileDir", SetOutFileDir },
            { "setWaitSecondsForWorkerToExit", SetWaitSecondsForWorkerToExit },
            { "setWorkerEncoding", SetWorkerEncoding },
            { "setWorkerMemoryLimit", SetWorkerMemoryLimit },
            { "setDomain", SetDomain },
            { "setUser", SetUser },
            { "setPassword", SetPassword }
        };

        var err = Libs.ReadConfig(Consts.CONF_FILE, setterDict);

        if (err != null)
        {
            abort = abort ?? Libs.Abort;
            abort($"Configuration Error: {err}");
        }

        ResolvePaths();

        if (DisplayName == null || DisplayName.Length == 0)
        {
            DisplayName = ServiceName;
        }
    }
示例#12
0
        public List <Libs> GetAllLibs()
        {
            List <Libs> output = new List <Libs>();

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    SqlCommand    cmd    = new SqlCommand(SQL_GetAllLibs, connection);
                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        Libs l = new Libs();
                        l.responseId = Convert.ToInt32(reader["responseId"]);
                        l.Name       = Convert.ToString(reader["name"]);
                        l.InputOne   = Convert.ToString(reader["inputOne"]);
                        l.InputTwo   = Convert.ToString(reader["inputTwo"]);
                        l.InputThree = Convert.ToString(reader["inputThree"]);
                        l.InputFour  = Convert.ToString(reader["inputFour"]);
                        l.InputFive  = Convert.ToString(reader["inputFive"]);

                        output.Add(l);
                    }
                }
            }
            catch (SqlException ex)
            {
                throw;
            }
            return(output);
        }
示例#13
0
        public override string ToString()
        {
            var result = new StringBuilder();

            if (Desc.HasValue)
            {
                SonarHelpers.AppendUrl(result, "desc", Desc.ToString().ToLowerInvariant());
            }
            SonarHelpers.AppendUrl(result, "format", Format);
            SonarHelpers.AppendUrl(result, "key", Key);
            if (Libs.HasValue)
            {
                SonarHelpers.AppendUrl(result, "libs", Libs.ToString().ToLowerInvariant());
            }
            SonarHelpers.AppendUrl(result, "search", Search);
            if (Subprojects.HasValue)
            {
                SonarHelpers.AppendUrl(result, "subprojects", Subprojects.ToString().ToLowerInvariant());
            }
            if (Versions != null)
            {
                SonarHelpers.AppendUrl(result, "versions", Versions.ToString().Substring(1));
            }
            if (Views.HasValue)
            {
                SonarHelpers.AppendUrl(result, "views", Views.ToString().ToLowerInvariant());
            }

            return(result.Length > 0 ? "?" + result : string.Empty);
        }
示例#14
0
        public ApiResult <Boolean> UpdateProfile(User Item)
        {
            ApiResult <Boolean> Rs = new ApiResult <Boolean>();

            try
            {
                DbProvider.SetCommandText("sp_User_UpdateProfile", CommandType.StoredProcedure);
                DbProvider.AddParameter("InJson", Libs.SerializeObject(Item), SqlDbType.NVarChar);

                DbProvider.AddParameter("ErrorCode", DBNull.Value, SqlDbType.NVarChar, 100, ParameterDirection.Output);
                DbProvider.AddParameter("ReturnMsg", DBNull.Value, SqlDbType.NVarChar, 4000, ParameterDirection.Output);

                DbProvider.ExecuteNonQuery();

                string errorCode = DbProvider.Command.Parameters["ErrorCode"].Value.ToString();

                if (!errorCode.Equals(Constants.SUCCESS))
                {
                    Rs.Failed(new ErrorObject()
                    {
                        Code        = DbProvider.Command.Parameters["ErrorCode"].Value.ToString(),
                        Description = DbProvider.Command.Parameters["ReturnMsg"].Value.ToString()
                    });
                }
            }
            catch (Exception ex)
            {
                Rs.Failed(new ErrorObject {
                    Code        = "EX",
                    Description = ex.ToString()
                });
            }

            return(Rs);
        }
示例#15
0
        public static List <ParallelSearchResult> ArrayThreadTask(object paramObj)
        {
            ParallelSearchThreadParam param =
                (ParallelSearchThreadParam)paramObj;
            //Слово для поиска в верхнем регистре
            string wordUpper = param.wordPattern.Trim().ToUpper();
            //Результаты поиска в одном потоке
            List <ParallelSearchResult> Result = new
                                                 List <ParallelSearchResult>();

            //Перебор всех слов во временном списке данного потока
            foreach (string str in param.tempList)
            {
                //Вычисление расстояния Дамерау-Левенштейна
                int dist = Libs.Distance(str.ToUpper(), wordUpper);
                if (dist <= param.maxDist)
                {
                    ParallelSearchResult temp = new ParallelSearchResult()
                    {
                        word      = str,
                        dist      = dist,
                        ThreadNum = param.ThreadNum
                    };
                    Result.Add(temp);
                }
            }
            return(Result);
        }
示例#16
0
        public static void WriteDistance(string str1Param, string str2Param)
        {
            int d = Libs.Distance(str1Param, str2Param);

            Console.WriteLine("'" + str1Param + "','" +
                              str2Param + "' -> " + d.ToString());
        }
示例#17
0
        /// <summary>
        /// Handle messaging with a single client.
        /// </summary>
        /// <param name="o"></param>
        static void ConnectionListener(object o)
        {
            int       id = (int)o;
            TcpClient client;

            lock (_lock) client = clients[id];

            NetworkStream stream = client.GetStream();

            byte[] buffer = new byte[client.ReceiveBufferSize];

            try
            {
                while (!exit)
                {
                    int bytesRead = stream.Read(buffer, 0, client.ReceiveBufferSize);

                    if (bytesRead == 0)
                    {
                        break;
                    }

                    ReceiveMessage(id, Message.FromBytes(buffer));
                }
            }
            catch (IOException e)
            {
                Libs.StatusMessage(e.Message, StatusType.FAILURE);
            }

            Libs.StatusMessage("Lost connection with the client.");
        }
示例#18
0
    private static int InstallService(Conf conf)
    {
        ServiceController sc;

        if ((sc = SvcUtils.CreateSvc(conf)) == null)
        {
            Libs.Print($"Failed to install Service \"{conf.ServiceName}\"");
            return(1);
        }

        var ss = $"Installed Service \"{conf.ServiceName}\"";

        Libs.Print(ss);
        Log(ss, false);
        Log("");

        var err = SvcUtils.SetSvcDescription(conf);

        if (err != null)
        {
            err = $"Failed to set description for Service \"{conf.ServiceName}\": {err}";
            Libs.Print(err);
            Libs.Print("Please run `svc remove` to remove the Service");
            Log(err);
            return(1);
        }

        return(StartService(sc));
    }
示例#19
0
        public ApiResult <UpdatePasswordViewModel> UpdatePassword(UpdatePasswordViewModel model)
        {
            var dbResult = new ApiResult <UpdatePasswordViewModel>();

            try
            {
                // Validate dữ liệu
                if (!ValidateUpdatePassword(model).Succeeded)
                {
                    return(ValidateUpdatePassword(model));
                }

                // Đặt lại mật khẩu trong database
                model.NewPassword = Libs.GetMd5(model.NewPassword + EncryptCore.PassKey);
                model.NewPassword = model.NewPassword;

                dbResult = userDAL.UpdatePassword(model);

                return(dbResult);
            }
            catch (Exception ex)
            {
                dbResult.Failed(new ErrorObject()
                {
                    Code        = Constants.ERR_EXCEPTION,
                    Description = ex.Message
                });
                return(dbResult);
            }
        }
示例#20
0
        public bool CreateLib(Libs newProject)
        {
            try
            {
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    conn.Open();

                    SqlCommand cmd = new SqlCommand(SQL_CreateLib, conn);
                    cmd.Parameters.AddWithValue("@name", newProject.Name);
                    cmd.Parameters.AddWithValue("@inputOne", newProject.InputOne);
                    cmd.Parameters.AddWithValue("@inputTwo", newProject.InputTwo);
                    cmd.Parameters.AddWithValue("@inputThree", newProject.InputThree);
                    cmd.Parameters.AddWithValue("@inputFour", newProject.InputFour);
                    cmd.Parameters.AddWithValue("@inputFive", newProject.InputFive);

                    int result = cmd.ExecuteNonQuery();

                    return(result > 0);
                }
            }
            catch (SqlException ex)
            {
                throw;
            }
        }
示例#21
0
 /// <summary>
 /// Set the color of the users messages.
 /// </summary>
 /// <param name="args"></param>
 static void CommandColor(string[] args)
 {
     if (args.Length > 0)
     {
         int newColor;
         if (int.TryParse(args[0], out newColor))
         {
             if (newColor >= 0 && newColor < 16)
             {
                 color = newColor;
             }
             else
             {
                 Libs.StatusMessage("Color has to be between 0-15", StatusType.FAILURE);
             }
         }
         else
         {
             Libs.StatusMessage("Invalid argument: " + args[0], StatusType.FAILURE);
         }
     }
     else
     {
         Libs.StatusMessage("Invalid number of arguments!", StatusType.FAILURE);
     }
 }
示例#22
0
        public Libs GetLibById(int id)
        {
            Libs output = new Libs();

            try
            {
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    connection.Open();

                    SqlCommand cmd = new SqlCommand(SQL_GetLibById, connection);
                    cmd.Parameters.AddWithValue("@id", id);
                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        Libs l = new Libs();
                        l.responseId = Convert.ToInt32(reader["responseId"]);
                        l.Name       = Convert.ToString(reader["name"]);
                        l.InputOne   = Convert.ToString(reader["inputOne"]);
                        l.InputTwo   = Convert.ToString(reader["inputTwo"]);
                        l.InputThree = Convert.ToString(reader["inputThree"]);
                        l.InputFour  = Convert.ToString(reader["inputFour"]);
                        l.InputFive  = Convert.ToString(reader["inputFive"]);

                        output = l;
                    }
                }
            }
            catch (SqlException ex)
            {
                throw;
            }
            return(output);
        }
示例#23
0
    private static void SetSvcDescription(Conf conf)
    {
        var    description = $"{conf.Description} @<{Libs.GetCwd()}>";
        var    scArgs      = $"description \"{conf.ServiceName}\" \"{description}\"";
        string err;

        Libs.Exec("sc", scArgs);
        try
        {
            var mngObj = GetServiceManagementObjectByName(conf.ServiceName);
            if (mngObj != null && mngObj["Description"].ToString() == description)
            {
                return;
            }

            err = "unknown reason";
        }
        catch (Exception ex)
        {
            err = ex.ToString();
        }

        err = $"Failed to set description for Service \"{conf.ServiceName}\": {err}";
        AddLog("ERROR", err);
        Libs.Abort($"{err}\r\nPlease run `svc remove` to remove the Service");
    }
示例#24
0
    protected override void OnStart(string[] args)
    {
        try
        {
            var svcDescription = SvcUtils.GetServiceDescriptionInSvcBin();
            var i   = svcDescription.LastIndexOf('<') + 1;
            var n   = svcDescription.Length - 1 - i;
            var cwd = svcDescription.Substring(i, n);
            Libs.SetCwd(cwd);
        }
        catch (Exception ex)
        {
            Libs.Dump($"Failed to set cwd from service's description:\r\n{ex}");
            Environment.Exit(1);
        }

        Conf = new Conf(false);

        try
        {
            Worker = new Worker(Conf, true);
            Worker.Start();
        }
        catch (Exception ex)
        {
            Conf.Abort($"Failed to start the worker:\r\n{ex}");
        }
    }
示例#25
0
    public static void InstallService(Conf conf)
    {
        var depend = conf.Dependencies.AddUniq(Consts.NECESSARY_DEPENDENCY, '/');

        // add "[svc]" to DisplayName to avoid "ServiceName == DisplayName" (which cases error in win7)
        var scArgs = $"create \"{conf.ServiceName}\" binPath= \"{Libs.BinPath}\" start= auto "
                     + $"DisplayName= \"[svc] {conf.DisplayName}\" depend= \"{depend}\"";

        if (conf.User.Length > 0)
        {
            var obj = (conf.Domain.Length > 0) ? $"{conf.Domain}\\{conf.User}" : conf.User;
            scArgs = $"{scArgs} obj= \"{obj}\" password= \"{conf.Password}\"";
        }

        Libs.Exec("sc", scArgs);

        var sc = GetServiceController(conf.ServiceName);

        if (sc == null)
        {
            Libs.Abort($"Failed to install Service \"{conf.ServiceName}\"");
        }

        var msg = $"Installed Service \"{conf.ServiceName}\"";

        Console.WriteLine(msg);
        AddLog("INFO", msg, false);
        AddLog("INFO", "");

        SetSvcDescription(conf);

        sc.StartService();
    }
示例#26
0
        public static Libs LoadJson()
        {
            using StreamReader r = new StreamReader("libman.json");
            string json = r.ReadToEnd();

            Libs = JsonConvert.DeserializeObject <Libs>(json);
            return(Libs);
        }
示例#27
0
 /// <summary>
 /// Thread for handling inputs by the host.
 /// </summary>
 /// <param name="o"></param>
 static void InputHandler()
 {
     while (!exit)
     {
         InputParser(Console.ReadLine());
     }
     Libs.StatusMessage("Input thread stopped.");
 }
示例#28
0
        public IHttpActionResult ChangePassword(ChangePWModel Item)
        {
            Item.NewPassword = Libs.GetMd5(Item.NewPassword + EncryptCore.PassKey);
            Item.OldPassword = Libs.GetMd5(Item.OldPassword + EncryptCore.PassKey);

            ApiResult <bool> rs = userDAL.ChangePassword(UserInfo.Id, Item);

            return(rs.Succeeded ? Ok(rs) : (IHttpActionResult)Content(HttpStatusCode.BadRequest, rs));
        }
示例#29
0
        public async Task <IEnumerable <Users> > GetLangs()
        {
            //todo
            var a     = Libs.CreateToken();
            var langs = await DbContext.Users.AsNoTracking().ToListAsync();

            return(langs);
            //return null;
        }
示例#30
0
    public void Cd()
    {
        if (!Directory.Exists(ConfDir))
        {
            Libs.Abort($"Service directory \"{ConfDir}\" not exists");
        }

        Libs.SetCwd(ConfDir);
    }
示例#31
0
        // http://twilio-queues.ngrok.io/Home/SayHello
        public void SayHello(Libs.Message incomingMessage)
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            using (var connection = factory.CreateConnection())
            {
                using (var channel = connection.CreateModel())
                {
                    channel.QueueDeclare("messages", false, false, false, null);
                    var message = JsonConvert.SerializeObject(incomingMessage);
                    var body = Encoding.UTF8.GetBytes(message);

                    channel.BasicPublish("", "messages", null, body);
                }
            }
        }