Пример #1
0
        internal ConfigObj select(string key)
        {
            string txtQuery = string.Format("SELECT * FROM {0} WHERE key = @key", this.tableName);

            try
            {
                ConfigObj data = new ConfigObj();
                using (SQLiteConnection c = new SQLiteConnection(sqlite.ConnectionString))
                {
                    c.Open();
                    using (SQLiteCommand cmd = new SQLiteCommand(txtQuery, c))
                    {
                        cmd.Parameters.AddWithValue("@key", key);
                        using (SQLiteDataReader dr = cmd.ExecuteReader())
                        {
                            if (dr.Read())
                            {
                                data.id    = Convert.ToInt32(dr["id"]);
                                data.key   = dr["key"].ToString();
                                data.value = dr["value"].ToString();
                            }
                        }
                    }
                }
                return(data);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #2
0
        internal void save(ConfigObj obj)
        {
            string txtQuery = string.Empty;

            // only update
            txtQuery = string.Format("UPDATE {0} SET ", this.tableName);
            string values    = string.Format("value=@value ");
            string condition = string.Format("WHERE id=@id");

            txtQuery = txtQuery + values + condition;
            using (SQLiteConnection c = new SQLiteConnection(sqlite.ConnectionString))
            {
                c.Open();
                using (SQLiteCommand cmd = new SQLiteCommand(txtQuery, c))
                {
                    cmd.Parameters.AddWithValue("@id", obj.id);
                    cmd.Parameters.AddWithValue("@value", obj.value);
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
        }
Пример #3
0
        void SetupConfig()
        {
            if (this.loaded)
            {
                return;
            }

            LoadConfig();
            this.configPath = Manager.ConfigPath + string.Format("\\{0}.json", Name);
            this.config     = JsonConvert.DeserializeObject <ConfigObj>((string)JsonConvert.SerializeObject(Config["Config"]).ToString());

            // This all seems
            try
            {
                this.factions = Interface.GetMod().DataFileSystem.ReadObject <List <Faction> >(this.factionDatafile);
            }
            catch (Exception e)
            {
                this.factions = new List <Faction>();
                this.SaveData();
            }

            if (this.factions == null)
            {
                this.factions = new List <Faction>();
            }

            this.loaded = true;
        }
Пример #4
0
        /// <summary>
        /// Reload Config File <type>
        /// </summary>
        /// <param name="args"></param>
        private void CommandIReload(CommandArgs args)
        {
            if (NPCManager.CustomNPCInvasion.invasionStarted)
            {
                NPCManager.CustomNPCInvasion.StopInvasion();
            }

            try
            {
                if (File.Exists(filepath))
                {
                    ConfigObj = new CustomNPCConfig();
                    ConfigObj = CustomNPCConfig.Read(filepath);
                    return;
                }
                else
                {
                    TShock.Log.ConsoleError("Config not found. Creating new one");
                    ConfigObj.Write(filepath);
                    return;
                }
            }
            catch (Exception ex)
            {
                TShock.Log.ConsoleError(ex.Message);
                return;
            }
        }
Пример #5
0
 public static void InitConfig()
 {
     if (!File.Exists(ConfigPath))
     {
         File.WriteAllText(ConfigPath, ToJson(new ConfigObj()));
     }
     CurrentConfig = FromJSON <ConfigObj>(File.ReadAllText(ConfigPath));
 }
Пример #6
0
        /// <summary>
        /// Sends a heart-beat to the server, while also checking for updates
        /// </summary>
        public void runHeartBeat()
        {
            Boolean hasNewVersion = false;

            Constants.STATIC_RUN_COUNTER++;
            Utils util = new Utils();

            try
            {
                ConfigObj cfg = util.readConfig();
                if (cfg != null && cfg.remoteTarget != null && cfg.remoteServer != null && cfg.strId != null)
                {
                    String data = util.getUrlStatusCode(cfg.remoteTarget);

                    HeartbeatData h = new HeartbeatData();

                    h.downloadSpeed = WebUtil.DownloadSpeed(false);
                    runUploadTrafficSensor(1024, out h.uploadSpeed);
                    h.assVersion   = util.getAssemblyVersion();
                    h.errorCounter = Constants.STATIC_ERROR_COUNTER;
                    h.runCounter   = Constants.STATIC_RUN_COUNTER;
                    h.strId        = cfg.strId;
                    h.version      = cfg.version;
                    string json = JsonConvert.SerializeObject(h);

                    String link = cfg.remoteServer + "?action=ACK&data=" + data + "&version=" + util.getAssemblyVersion() + "&strId=" + cfg.strId + "&errorcounter=" + Constants.STATIC_ERROR_COUNTER + "&runcounter=" + Constants.STATIC_RUN_COUNTER;
                    link = link.Trim();
                    String code = util.getUrlStatusCode(link);
                    util.writeToLogFile(link);
                    if (code != null)
                    {
                        if (!code.Equals("OK"))
                        {
                            Constants.STATIC_ERROR_COUNTER++;
                        }
                        else
                        {
                            hasNewVersion = runDownloadTrafficSensor();
                            runUploadTrafficSensor();
                            if (hasNewVersion)
                            {
                                updateService();
                            }
                        }
                    }
                    else
                    {
                        Constants.STATIC_ERROR_COUNTER++;
                    }
                }
            }
            catch (Exception e)
            {
                Constants.STATIC_ERROR_COUNTER++;
                util.writeEventLog(e.Message);
                util.writeEventLog(e.StackTrace);
            }
        }
Пример #7
0
        public static ConfigObj load(string path)
        {
            ConfigObj config = null;

            using (var input = new StreamReader(path, Encoding.UTF8))
            {
                var deserializer = new DeserializerBuilder().Build();
                config = deserializer.Deserialize <ConfigObj>(input);
            }
            return(config);
        }
Пример #8
0
        void CreateDefaultConfig()
        {
            ConfigObj localConfig = new ConfigObj();

            localConfig.countdown    = 10;
            localConfig.safeDistance = 0;

            localConfig.addMessage("welcome", new List <string>()
            {
                "Welcome to spawn!"
            });
            localConfig.addMessage("countdown", new List <string>()
            {
                "You will teleport to spawn in {0} seconds."
            });
            localConfig.addMessage("spawn", new List <string>()
            {
                "You have teleported to spawn."
            });
            localConfig.addMessage("setSpawn", new List <string>()
            {
                "You have set the server spawn point."
            });
            localConfig.addMessage("noSpawn", new List <string>()
            {
                "You have not set the server spawn point yet.", "Type /setspawn to set a spawn."
            });

            localConfig.addMessage("pendingTeleport", new List <string>()
            {
                "You already have a pending teleport."
            });
            localConfig.addMessage("canceledFromDamage", new List <string>()
            {
                "You've been hit! Your teleport has been canceled."
            });

            localConfig.addMessage("helpSpawn", new List <string>()
            {
                "Use /spawn to teleport to spawn."
            });
            localConfig.addMessage("helpSetSpawn", new List <string>()
            {
                "Use /setspawn to set the server spawn point."
            });

            this.config      = localConfig;
            Config["Config"] = this.config;
            SaveConfig();

            this.SetupConfig();
        }
Пример #9
0
        /// <summary>
        /// Measures the download speed
        /// </summary>
        /// <returns></returns>
        public bool runDownloadTrafficSensor(out double speed)
        {
            speed = -1;

            Boolean   hasNewVersion = false;
            Utils     util          = new Utils();
            Stopwatch sw            = new Stopwatch();
            String    content       = null;
            long      elapsed       = -1L;

            try
            {
                ConfigObj cfg = util.readConfig();

                sw.Start();
                content = util.getTextFromUrl(cfg.downloadUrl);
                sw.Stop();
                if (content.Length == 1048586)
                {
                    elapsed = sw.ElapsedMilliseconds;
                    long size = Encoding.ASCII.GetByteCount(content);
                    speed = size / sw.Elapsed.TotalSeconds / 1024;

                    util.getUrlStatusCode(cfg.remoteServer + "?action=DW&version=" + cfg.version + "&strId=" + cfg.strId + "&elapsed=" + elapsed);

                    // Check if the current service version is equals to server service version

                    String[] words         = content.Split(' ');
                    String   serverVersion = null;
                    if (words.Length > 0)
                    {
                        serverVersion = words[0];

                        if (!serverVersion.Equals(cfg.version))
                        {
                            hasNewVersion = true;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                util.writeEventLog(e.Message);
                util.writeEventLog(e.StackTrace);
            }

            return(hasNewVersion);
        }
Пример #10
0
        /// <summary>
        /// Measures the upload speed
        /// </summary>
        public void runUploadTrafficSensor(long uploadSize, out double speed)
        {
            speed = -1;
            Stopwatch sw      = new Stopwatch();
            Utils     util    = new Utils();
            String    content = null;

            byte[] result  = null;
            long   elapsed = -1L;

            try
            {
                ConfigObj            cfg    = util.readConfig();
                System.Net.WebClient Client = new System.Net.WebClient();
                Client.Headers.Add("Content-Type", "binary/octet-stream");

                byte[] updata = new byte[uploadSize];
                Random rng    = new Random();
                for (int i = 0; i < uploadSize; i++)
                {
                    updata[i] = (byte)rng.Next(0, 255);
                }

                sw.Start();
                result = Client.UploadData(cfg.uploadUrl, "POST", updata);
                sw.Stop();

                elapsed = sw.ElapsedMilliseconds;
                speed   = uploadSize / sw.Elapsed.TotalSeconds / 1024.0;

                content = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
                if (content.Equals("OK"))
                {
                    util.getUrlStatusCode(cfg.remoteServer + "?action=UP&version=" + cfg.version + "&strId=" + cfg.strId + "&elapsed=" + elapsed);
                }
            }
            catch (Exception e)
            {
                util.writeEventLog(e.Message);
                util.writeEventLog(e.StackTrace);
            }
        }
Пример #11
0
        public ConfigObj readConfig()
        {
            ConfigObj config = new ConfigObj();

            try
            {
                StringBuilder output = new StringBuilder();

                String xmlString = getTextFromFile(getConfPath(Constants.CONF_PATH));
                if (xmlString != null)
                {
                    config = parseConfig(xmlString);
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(config);
        }
Пример #12
0
 /// <summary>
 /// Config for Custom Mob Invasions
 /// </summary>
 private void SetupConfig()
 {
     try
     {
         if (File.Exists(filepath))
         {
             ConfigObj = new CustomNPCConfig();
             ConfigObj = CustomNPCConfig.Read(filepath);
             return;
         }
         else
         {
             TShock.Log.ConsoleError("Config not found. Creating new one");
             ConfigObj.Write(filepath);
             return;
         }
     }
     catch (Exception ex)
     {
         TShock.Log.ConsoleError(ex.Message);
         return;
     }
 }
Пример #13
0
        public void writeConfig(ConfigObj config, String configPath)
        {
            StringBuilder sb = null;

            try
            {
                sb = new StringBuilder();

                sb.Append("<?xml version='1.0' encoding='UTF-8' standalone='yes'?>\n");
                sb.Append(" <openaudit>\n");
                sb.Append("     <config strId='" + config.strId + "' remoteServer='" + config.remoteServer + "' remoteTarget='" + config.remoteTarget + "' version='" + config.version + "' uploadUrl='" + config.uploadUrl + "' downloadUrl='" + config.downloadUrl + "' >\n");
                sb.Append("     </config>\n");
                sb.Append(" </openaudit>\n");

                if (File.Exists(configPath))
                {
                    File.Delete(configPath);
                }
                using (StreamWriter outfile = new StreamWriter(configPath))
                {
                    outfile.Write(sb.ToString());
                    outfile.Close();
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (sb != null)
                {
                    sb = null;
                }
            }
        }
Пример #14
0
        public ConfigObj parseConfig(String configXml)
        {
            ConfigObj config = new ConfigObj();

            try
            {
                using (XmlReader reader = XmlReader.Create(new StringReader(configXml)))
                {
                    reader.ReadToFollowing("config");
                    config.strId        = reader.GetAttribute("strId");
                    config.remoteServer = reader.GetAttribute("remoteServer");
                    config.remoteTarget = reader.GetAttribute("remoteTarget");
                    config.downloadUrl  = reader.GetAttribute("downloadUrl");
                    config.uploadUrl    = reader.GetAttribute("uploadUrl");
                    config.version      = reader.GetAttribute("version");
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(config);
        }
Пример #15
0
        private void registerConfig(String id)
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                buttonContinue.Enabled = false;
                textBoxDetails.Text    = "PROCESSING...";
                if (id != null && id.Length > 3)
                {
                    Utils     util = new Utils();
                    ConfigObj cfg  = util.readConfig();
                    if (cfg != null && cfg.remoteServer != null && cfg.remoteServer.Length > 12)
                    {
                        String newCfg = util.getTextFromUrl(cfg.remoteServer + "?action=config&data=" + textBoxId.Text + "&version=" + util.getAssemblyVersion());

                        if (newCfg != null)
                        {
                            cfg         = util.parseConfig(newCfg);
                            cfg.version = util.getAssemblyVersion();
                            if (cfg != null && cfg.remoteServer != null && cfg.remoteTarget != null && cfg.remoteTarget != null)
                            {
                                cfg.version = util.getAssemblyVersion();
                                util.writeConfig(cfg, util.getConfPath(Constants.CONF_PATH));
                                cfg = util.readConfig();
                                if (cfg != null && cfg.remoteTarget.Length > 12)
                                {
                                    String code = util.getUrlStatusCode(cfg.remoteTarget);
                                    if (code.Equals("OK"))
                                    {
                                        textBoxDetails.Text = "SUCCESS! ";
                                        Start();
                                        Environment.Exit(0);
                                    }
                                    else
                                    {
                                        sb.Append("Unable to reach remote target! ");
                                    }
                                }
                            }
                            else
                            {
                                sb.Append("Unable to reach remote server! ");
                            }
                        }
                        else
                        {
                            sb.Append("Invalid config file. ");
                        }
                    }
                    else
                    {
                        sb.Append("Unable to read pre-config file. ");
                    }
                }
                else
                {
                    sb.Append("ID cannot be null! ");
                    buttonContinue.Enabled = true;
                }

                if (sb.Length > 0)
                {
                    textBoxDetails.Text = (sb.ToString());
                }
            }
            catch (Exception exc)
            {
                sb.Append(" Failed at initialization. " + exc.Message);
                buttonContinue.Enabled = true;
                textBoxDetails.Text    = (sb.ToString());
            }
        }
Пример #16
0
        void CreateDefaultConfig()
        {
            ConfigObj localConfig = new ConfigObj();

            localConfig.addMessage(
                "help",
                new List <string>()
            {
                "To create a faction, type \"/faction create <name>\".",
                "To request to join a faction, type \"/faction join <name>\".",
                "To invite, type \"/faction invite <player>\".",
                "To get faction info, type \"/faction info <name>\".",
                "You can also use \"/f\"."
            }
                );
            localConfig.addMessage("created", new List <string>()
            {
                "You have created the \"{0}\" faction."
            });
            localConfig.addMessage("notCreated", new List <string>()
            {
                "The \"{0}\" faction doesn't exists."
            });
            localConfig.addMessage("alreadyCreated", new List <string>()
            {
                "The \"{0}\" faction already exists."
            });
            localConfig.addMessage("alreadyInFaction", new List <string>()
            {
                "You are already a member of a faction."
            });
            localConfig.addMessage("invalidCommand", new List <string>()
            {
                "You ran the \"{0}\" command incorrectly. Type \"/faction help\" to get help"
            });
            localConfig.addMessage("invitationSent", new List <string>()
            {
                "You have invited \"{0}\" to your faction."
            });
            localConfig.addMessage(
                "invitationReceived",
                new List <string>()
            {
                "You have been invited to the \"{0}\" faction.",
                "To accept, type \"/faction join {0}\".",
                "To reject, type \"/faction reject {0}\".",
            }
                );
            localConfig.addMessage("invitationRejected", new List <string>()
            {
                "You have rejected the invitiation from the \"{0}\" faction."
            });
            localConfig.addMessage("requestSent", new List <string>()
            {
                "You have requested to join the \"{0}\" faction."
            });
            localConfig.addMessage(
                "requestReceived",
                new List <string>()
            {
                "\"{0}\" is requesting to join your faction.",
                "Accept with \"/faction accept {0}\".",
                "Deny with \"/faction deny {0}\"."
            }
                );
            localConfig.addMessage("notInFaction", new List <string>()
            {
                "You are not a member of a faction."
            });
            localConfig.addMessage("notOnline", new List <string>()
            {
                "\"{0}\" is either not online, or not a real user."
            });
            localConfig.addMessage("notAcceptee", new List <string>()
            {
                "\"{0}\" has not requested to join your group."
            });
            localConfig.addMessage("membershipGranted", new List <string>()
            {
                "You have been accepted into the \"{0}\" faction."
            });
            localConfig.addMessage("membershipDenied", new List <string>()
            {
                "You have been denied from the \"{0}\" faction."
            });
            localConfig.addMessage("playerAccepted", new List <string>()
            {
                "\"{0}\" has been added to your faction."
            });
            localConfig.addMessage("playerDenied", new List <string>()
            {
                "\"{0}\" has NOT been added to your faction."
            });
            localConfig.addMessage("playerKicked", new List <string>()
            {
                "You have kicked \"{0}\" from your faction."
            });
            localConfig.addMessage("playerKickReceived", new List <string>()
            {
                "You have been kicked from the \"{0}\" faction."
            });
            localConfig.addMessage(
                "factionInfo",
                new List <string>()
            {
                "The \"{0}\" faction:",
                "Owner: {1}",
                "Members: {2}"
            }
                );

            this.config      = localConfig;
            Config["Config"] = this.config;
            SaveConfig();

            this.SetupConfig();
        }
Пример #17
0
        static void Main(string[] args)
        {
            try
            {
retry:

                util.writeToLogFile("Starting Update");

                // Hide console window ( update silently )
                var handle = GetConsoleWindow();
                ShowWindow(handle, SW_HIDE);

                // Check for an internet connection
                util.writeToLogFile("Testing Internet Connection");

                if (NetworkInterface.GetIsNetworkAvailable() &&
                    new Ping().Send(EIGURL).Status == IPStatus.Success)
                {
                    util.writeToLogFile("There is Internet Connection");

                    // Check if services are stopped, if not stop them
                    util.writeToLogFile("Stopping services");
                    stopService("open-audit-service");
                    stopService("open-audit-check-service");

                    // Download Files
                    try
                    {
                        util.writeToLogFile("Creating temporary directory");
                        if (Directory.Exists(util.getPfPath() + "\\temp"))
                        {
                            Directory.Delete(util.getPfPath() + "\\temp", true);
                        }
                        Directory.CreateDirectory(util.getPfPath() + "\\temp");

                        util.writeToLogFile("Downloading files...");
                        String    mainPath  = EIGURL + "open_audit/update/";
                        WebClient webClient = new WebClient();
                        webClient.DownloadFile(mainPath + "open-audit-service.exe", util.getPfPath() + "\\temp\\open-audit-service.exe");
                        webClient.DownloadFile(mainPath + "open-audit-config.exe", util.getPfPath() + "\\temp\\open-audit-config.exe");
                        webClient.DownloadFile(mainPath + "open-audit-check-service.exe", util.getPfPath() + "\\temp\\open-audit-check-service.exe");
                        webClient.DownloadFile(mainPath + "open-audit.conf", util.getPfPath() + "\\temp\\open-audit.conf");
                        webClient.DownloadFile(mainPath + "open-audit-lib.dll", util.getPfPath() + "\\temp\\open-audit-lib.dll");
                    }
                    catch (Exception e)
                    {
                        util.writeToLogFile(e.Message);
                        util.writeToLogFile(e.StackTrace);
                        Thread.Sleep(30000);
                        goto retry;
                    }

                    util.writeToLogFile("Updating");

                    //BKP Obj
                    ConfigObj config = util.readConfig();

                    int error_count = 0;
                    while (!replaceFiles() && error_count < 5)
                    {
                        error_count++;
                        Thread.Sleep(3000);
                    }

                    if (error_count < 5)
                    {
                        ConfigObj newConfig = util.readConfig();
                        newConfig.strId = config.strId;
                        util.writeConfig(newConfig, util.getConfPath(Constants.CONF_PATH));

                        // Clean temp directory
                        util.writeToLogFile("Cleaning Temporary Files");
                        Directory.Delete(util.getPfPath() + "\\temp", true);

                        // Start Services
                        util.writeToLogFile("Starting services again");
                        startService("open-audit-service");
                        startService("open-audit-check-service");
                        util.writeToLogFile("DONE!");
                    }
                    else
                    {
                        util.writeToLogFile("Não foi possível atualizar os arquivos baixados, tentando novamente...");
                        Thread.Sleep(5000);
                        Main(null);
                    }
                }
                else
                {
                    util.writeToLogFile("There isn't internet connection, trying again in 30s");
                    Thread.Sleep(30000);
                    Main(null);
                }
            }
            catch (Exception e)
            {
                util.writeToLogFile(e.Message);
                util.writeToLogFile(e.StackTrace);
            }
        }