Example #1
0
        /// <summary>
        /// Sets the nessid (mediumid) in the decodes properties
        /// for the routing spec called 'hydromet-tools'
        /// Assuming there is a property name='sc:DCP_ADDRESS_0000'  that contains the
        /// nessid for routing a single site.
        /// </summary>
        /// <param name="svr"></param>
        /// <param name="siteid"></param>
        /// <returns></returns>
        private static bool UpdateNessidInRoutingProperties(PostgreSQL svr, string siteid)
        {
            // lookup mediumid in decodes
            var sql = "select id,platformdesignator,mediumid "
                      + " from platform P join transportmedium T "
                      + " on P.id = T.platformid "
                      + " where platformdesignator ~*'\\m" + siteid + "\\M'";

            var tbl = svr.Table("a", sql);

            if (tbl.Rows.Count != 1)
            {
                Logger.WriteLine("Error: could not find '" + siteid + "' in the DECODES database");
                return(false);
            }
            var mediumid = tbl.Rows[0]["mediumid"].ToString();

            // update medium id in routing spec property
            sql = "SELECT routingspecid, prop_name, prop_value "
                  + " FROM public.routingspecproperty "
                  + " where routingspecid in (select id from routingspec where name='hydromet-tools') "
                  + " and prop_name ='sc:DCP_ADDRESS_0000'";

            tbl = svr.Table("routingspecproperty", sql);
            if (tbl.Rows.Count != 1)
            {
                Logger.WriteLine("Error: could not find 'sc:DCP_ADDRESS_0000' in the DECODES database");
                return(false);
            }
            tbl.Rows[0]["prop_value"] = mediumid;

            return(svr.SaveTable(tbl) > 0);
        }
Example #2
0
        static void Main(string[] args)
        {
            Logger.EnableLogger(true);
            try
            {
                string fileName = GetFileName(args);

                HydrometInfoUtility.SetDefaultHydrometServer();

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.ThreadExit      += new EventHandler(Application_ThreadExit);
                Application.ApplicationExit += new EventHandler(Application_ApplicationExit);


                piscesForm1 = new PiscesForm(fileName);

                piscesForm1.FormClosed += new FormClosedEventHandler(explorerForm1_FormClosed);

                Application.Run(piscesForm1);

                PostgreSQL.ClearAllPools();
                FileUtility.CleanTempPath();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }
Example #3
0
        public static void Import(string serverIP, string database, string siteFilter, string networkListName)
        {
            string      fn    = @"C:\temp\mcf.xml";
            Performance perf  = new Performance();
            var         pnMcf = new McfDataSet();

            if (File.Exists(fn) && File.GetLastWriteTime(fn).Date != DateTime.Now.Date)
            { // read existing file.
                Logger.WriteLine("Reading existing XML");
                pnMcf.ReadXml(fn);
            }
            else
            {
                Logger.WriteLine("Reading csv files from MCF");
                pnMcf = McfUtility.GetDataSetFromCsvFiles(Globals.LocalConfigurationDataPath);
                pnMcf.WriteXml(fn);
            }

            DumpInfo(pnMcf);

            Application.DoEvents();

            Logger.WriteLine(serverIP);

            var                 cs      = PostgreSQL.CreateADConnectionString(serverIP, database, "decodes");
            PostgreSQL          svr     = new PostgreSQL(cs);
            var                 decodes = DecodesUtility.GetDataSet(svr);
            McfDecodesConverter c       = new McfDecodesConverter(svr, pnMcf, decodes);

            c.importMcf(siteFilter.Split(','), networkListName);

            UpdateSequences(svr);
        }
Example #4
0
        static int Main(string[] args)
        {
            Logger.EnableLogger();
            if (args.Length < 1 || args.Length > 2)
            {
                Console.WriteLine("Usage: HydrometNotifications.exe alarm_group [\"m/d/yyyy hh:mm\"]");
                Console.WriteLine("Where: alarm_group argument is required");
                Console.WriteLine("[m/d/yyyy] is an optional date argument the default is now");
                Console.WriteLine("");
                return(-1);
            }

            Performance perf = new Performance();

            var alarms = new AlarmGroup(args[0]);

            DateTime t = DateTime.Now;

            if (args.Length == 2)
            {
                t = DateTime.Parse(args[1]);
            }
            else
            if (alarms.Interval.ToLower() == "d")
            {
                t = DateTime.Now.Date.AddDays(-1); // hydromet daily
            }


            alarms.ProcessGroup(t);
            perf.Report();
            PostgreSQL.ClearAllPools();
            return(0);
        }
Example #5
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            PostgreSQL.Initizalize();
            Images.Initialize();
            Config.Initialize();

            t = new Auth();
            t.Authenticate += new AuthHandler(T_Authenticate);
            t.Icon          = Images.Get("login").ToIcon();

            Section section = Config.Section("Configuration");

            Utils.DB     = new PgSQL(Host: section.Key("Server").Value.Get <string>(), Database: "edds");
            Utils.PREFIX = "edds";

            if (Utils.DB.OpenConnection())
            {
                if (t.ShowDialog() == DialogResult.OK)
                {
                    Application.Run(new MainForm());
                }
            }
            else
            {
                FS.Notify.Error("Связь потеряно!");
            }
        }
Example #6
0
        static void Main(string[] args)
        {
            var svr = PostgreSQL.GetPostgresServer("timeseries", "lrgs1");
            var db  = new TimeSeriesDatabase(svr, Reclamation.TimeSeries.Parser.LookupOption.TableName);

            TimeSeriesCalculator c = new TimeSeriesCalculator(db, TimeInterval.Daily, "", "");

            CsvFile csv = new CsvFile(@"T:\PN6200\Hydromet\Data\rivers_canals_old.csv", CsvFile.FieldTypes.AllText);

            for (int i = 0; i < csv.Rows.Count; i++)
            {
                string siteID = csv.Rows[i]["cbtt"].ToString();
                string pcode  = csv.Rows[i]["pcode"].ToString();
                var    dep    = c.GetDependentCalculations(siteID, pcode);

                string msg = "";
                foreach (var item in dep)
                {
                    msg += " " + item.Name;
                }
                if (msg != "")
                {
                    Console.WriteLine(siteID + "_" + pcode + ": " + msg);
                }
            }
        }
Example #7
0
 public McfDecodesConverter(PostgreSQL svr, McfDataSet mcf, DecodesDataSet decodes)
 {
     this.svr     = svr;
     this.mcf     = mcf;
     this.decodes = decodes;
     m_converter  = new UnitConversion(mcf, decodes, svr);
 }
Example #8
0
        static void Main(string[] args)
        {
            //   Console.WriteLine(DateTime.Now.Ticks);

            // Logger.EnableLogger();
            var svr = PostgreSQL.GetPostgresServer("timeseries", "lrgs1");
            var db  = new TimeSeriesDatabase(svr, Reclamation.TimeSeries.Parser.LookupOption.TableName);


            CheckForDuplicates(db);
            var sc = db.GetSeriesCatalog();

            SortFoldersByName(db, "agrimet");
            //SortFoldersByName(db, "hydromet");

            //RenameUntitled(svr, db);
            // FixBlankInterval(db); // should be fixed in HydrometServer
            //FixSiteID(svr, sc);  //. should be fixed in HydrometServer

            // SetSeriesPropertyBasedOnSiteCatalog(db);

            FixFolderStructure(db, sc);

            //AssignProgramToInstant(db); // agrimet currently uses this to import
        }
Example #9
0
        public void Escape_Characters()
        {
            IEngine engine = new PostgreSQL();

            Assert.Equal('\"', engine.Options.EscapeStart);
            Assert.Equal('\"', engine.Options.EscapeEnd);
        }
Example #10
0
        /// <summary>
        /// 校验票据(数据库数据匹配)
        /// </summary>
        /// <param name="encryptToken">令牌</param>
        /// <returns></returns>
        private bool ValidateTicket(string encryptToken)
        {
            bool flag = false;

            try
            {
                //解密Token
                string strtoken = SunGolden.Encryption.DEncrypt.Decrypt(encryptToken);
                //
                var      index      = strtoken.IndexOf(",");
                var      indexend   = strtoken.LastIndexOf(",");
                string   str_mobile = strtoken.Substring(0, index);
                string   str_role   = strtoken.Substring(index + 1, 1);
                DateTime vaild_time = Convert.ToDateTime(strtoken.Substring(indexend + 1));
                //获取数据库用户信息
                PostgreSQL.OpenCon();//打开数据库
                string str_select = "select * from tb_user where mobile = @mobile;";
                var    para       = new DbParameter[1];
                para[0] = PostgreSQL.NewParameter("@mobile", str_mobile);
                var qUser = PostgreSQL.ExecuteTQuery <User>(str_select, null, para);
                PostgreSQL.CloseCon(); //关闭数据库
                if (qUser != null)     //存在
                {
                    flag = (DateTime.Now <= vaild_time)? true : false;
                }
            }
            catch (Exception ex)
            {
                flag = false;
            }
            return(flag);
        }
Example #11
0
        public static DecodesDataSet GetDataSet(PostgreSQL svr)
        {
            var ds = new DecodesDataSet();

            for (int i = 0; i < tableNames.Length; i++)
            {
                string sql = "select * from " + tableNames[i];
                var    tbl = ds.Tables[tableNames[i]];

                // check for schema changes

                var tblx = svr.Table(tableNames[i], sql + " where 1=2");
                var cnx  = tblx.Columns.Cast <DataColumn>()
                           .Select(x => x.ColumnName).ToArray();
                var cn = tbl.Columns.Cast <DataColumn>()
                         .Select(x => x.ColumnName).ToArray();

                if (cnx.Length != cn.Length)
                {
                    Logger.WriteLine("database: " + String.Join(",", cnx));
                    Logger.WriteLine("dataset : " + String.Join(",", cn));
                }


                svr.FillTable(tbl, sql);

                if (tbl.Rows.Count > 0)
                {
                    Console.WriteLine("Notice Existing data. " + tableNames[i] + " has " + tbl.Rows.Count + " rows ");
                }
            }
            return(ds);
        }
Example #12
0
 public BooksDashboard(PostgreSQL db)
 {
     database = db;
     InitializeComponent();
     // initial connection to show all current rows
     this.RefreshData();
 }
Example #13
0
        public static BasicDBServer GetPGServer(string ipaddress = "localhost", string dbName = "nunit")
        {
            var cs = PostgreSQL.CreateADConnectionString(ipaddress, dbName);

            PostgreSQL svr = new PostgreSQL(cs);
            return svr;
        }
Example #14
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            PostgreSQL database = new PostgreSQL("postgres", "postgres", "localhost", "5432");

            Application.Run(new BooksDashboard(database));
        }
Example #15
0
        public static BasicDBServer GetPGServer(string ipaddress = "localhost", string dbName = "nunit")
        {
            var cs = PostgreSQL.CreateADConnectionString(ipaddress, dbName);

            PostgreSQL svr = new PostgreSQL(cs);

            return(svr);
        }
Example #16
0
 public UnitConversion(Reclamation.TimeSeries.Hydromet.McfDataSet mcf,
                       Reclamation.TimeSeries.Decodes.DecodesDataSet decodes,
                       PostgreSQL svr)
 {
     this.mcf     = mcf;
     this.decodes = decodes;
     this.svr     = svr;
 }
Example #17
0
        public object Register(User user)
        {
            string              token     = "";
            ResultMsg <User>    resultmsg = new ResultMsg <User>();
            HttpResponseMessage response  = new HttpResponseMessage();

            if (user.mobile.Length != 11 || !Regex.IsMatch(user.mobile, @"^[0-9]*[0-9][0-9]*$"))
            {
                resultmsg.status = false;
                resultmsg.msg    = "手机号必须是11位有效数字!";
                resultmsg.data   = null;
                token            = null;
            }
            else
            {
                PostgreSQL.OpenCon();//打开数据库
                DateTime time = DateTime.Now.Date.AddDays(30);
                //插入数据
                var    trans      = PostgreSQL.BeginTransaction();
                string str_insert = "insert into tb_user(name,mobile,im_pwd,\"role\") values(@name,@mobile,@im_pwd,@role);";
                try
                {
                    var para1 = new DbParameter[4];
                    para1[0] = PostgreSQL.NewParameter("@name", user.mobile);
                    para1[1] = PostgreSQL.NewParameter("@mobile", user.mobile);
                    para1[2] = PostgreSQL.NewParameter("@im_pwd", SunGolden.Encryption.DEncrypt.Encrypt(user.mobile));
                    para1[3] = PostgreSQL.NewParameter("@role", user.role);
                    var num = PostgreSQL.ExecuteNoneQuery(str_insert, trans, para1);
                    PostgreSQL.CommitTransaction(trans);
                    //重新查询
                    string str_select = "select * from tb_user where mobile = @mobile;";
                    var    para2      = new DbParameter[1];
                    para2[0] = PostgreSQL.NewParameter("@mobile", user.mobile);
                    var qUser = PostgreSQL.ExecuteTQuery <User>(str_select, null, para2);
                    //返回信息
                    resultmsg.status = true;
                    resultmsg.msg    = "登录成功!";
                    resultmsg.data   = qUser;
                    token            = SunGolden.Encryption.DEncrypt.Encrypt(user.mobile + "," + user.role + "," + time);
                }
                catch (Exception ex)
                {
                    PostgreSQL.RollbackTransaction(trans);
                    //返回信息
                    resultmsg.status = false;
                    resultmsg.msg    = "[ERROR] 数据库操作出现异常:" + ex.Message;
                    resultmsg.data   = null;
                    token            = null;
                }
                PostgreSQL.CloseCon();//关闭数据库
            }
            //添加响应头
            var resultObj = JsonConvert.SerializeObject(resultmsg, Formatting.Indented);

            response.Headers.Add("Token", token);
            response.Content = new StringContent(resultObj);
            return(response);
        }
Example #18
0
        public BlockParser()
        {
            Console.WriteLine($"start time {string.Format("{0:HH:mm:ss tt}", DateTime.Now) }");

            string        blockchainPath = @"C:\Users\johnn\AppData\Roaming\Bitcoin\testnet3\blocks\";
            DirectoryInfo di             = new DirectoryInfo(blockchainPath);

            FileInfo[] files = di.GetFiles("blk*.dat");

            Console.WriteLine($"{files.Length} files found");

            PostgreSQL postgreSql = new PostgreSQL();

            for (int i = 0; i < 10; ++i)
            {
                using (FileStream fs = new FileStream(files[i].FullName, FileMode.Open)) {
                    using (MemoryStream ms = new MemoryStream()) {
                        using (BinaryReader br = new BinaryReader(ms)) {
                            Console.WriteLine($"processing {files[i].Name} ({i}/{files.Length})");

                            double progress    = 0;
                            int    checkpoint  = 0;
                            long   blockOffset = 0;

                            UpdateProgress(progress, ref checkpoint);
                            fs.CopyTo(ms);
                            ms.Position = 0;

                            while (ms.Position < ms.Length)
                            {
                                blockOffset = ms.Position;

                                Block block = new Block();
                                block.ReadStream(br);

                                postgreSql.Insert(block, files[i].Name, blockOffset);

                                ms.Position = blockOffset + (block.size + (2 * sizeof(UInt32)));

                                progress = ((double)ms.Position / fs.Length) * 100;
                                if (progress >= checkpoint)
                                {
                                    UpdateProgress(progress, ref checkpoint);
                                }
                            }
                        }
                    }
                }
                Console.WriteLine("\n");
            }

            postgreSql.CreateIndexes();
            postgreSql.RemoveStaleBlocks();
            postgreSql.AddHeightColumn();

            Console.WriteLine($"end time; {string.Format("{0:HH:mm:ss tt}", DateTime.Now)}");
        }
Example #19
0
        /// <summary>
        /// 根据种植时间和当前作物获取当前时间的物候期
        /// </summary>
        /// <param name="date"></param>
        /// <param name="currentcrop"></param>
        /// <returns></returns>
        public int phentype(DateTime date, int currentcrop)
        {
            int phenophase = -1;

            if (DateTime.Now.Date < date)//判断种植日期
            {
                phenophase = -1;
            }
            else
            {
                TimeSpan sowdays1 = DateTime.Now.Date.Subtract(date);
                int      sowdays  = sowdays1.Days;
                //获取当前作物的物候
                string str_phen = "select id, phen_type,time from tb_phenophase where crop_type = @crop_type ;";
                var    para3    = new DbParameter[1];
                para3[0] = PostgreSQL.NewParameter("@crop_type", currentcrop);
                var q_phen = PostgreSQL.ExecuteTableQuery(str_phen, null, para3);
                if (q_phen != null && q_phen.Rows != null && q_phen.Rows.Count > 0)
                {
                    //作物的整个物候期时间
                    //object phen_sum = q_phen.Compute("sum(time)", "");
                    int time = Convert.ToInt16(q_phen.Rows[0]["time"]);
                    if (sowdays <= time && sowdays >= 0)
                    {
                        phenophase = Convert.ToInt16(q_phen.Rows[0]["id"]);
                    }
                    else
                    {
                        #region
                        //int[] sum = new int[q_phen.Rows.Count];
                        //int s = 0;
                        //for (int i = 0; i < q_phen.Rows.Count; i++)
                        //{
                        //    s += Convert.ToInt16(q_phen.Rows[i]["time"]);
                        //    sum[i] = s;
                        //}
                        #endregion
                        for (int i = 1; i < q_phen.Rows.Count; i++)
                        {
                            if (sowdays > Convert.ToInt16(q_phen.Rows[i - 1]["time"]) && sowdays <= Convert.ToInt16(q_phen.Rows[i]["time"]))
                            {
                                phenophase = Convert.ToInt16(q_phen.Rows[i - 1]["id"]);
                            }
                            else if (sowdays > Convert.ToInt16(q_phen.Rows[q_phen.Rows.Count - 1]["time"]))
                            {
                                phenophase = Convert.ToInt16(q_phen.Rows[q_phen.Rows.Count - 1]["id"]);
                            }
                        }
                    }
                }
                else
                {
                    phenophase = -1;
                }
            }
            return(phenophase);
        }
Example #20
0
        //public static void TruncateTablesaa(PostgreSQL svr)
        //{
        //    foreach (var tableName in tableNames)
        //    {
        //        string sql = "delete from " + tableName ;
        //        svr.RunSqlCommand(sql);
        //    }
        //}

        //    public static void AddEquipment(DecodesDataSet decodes)  {


        //        var e = decodes.equipmentmodel;
        //        var ep = decodes.equipmentproperty;

        //        e.AddequipmentmodelRow(1, "MCF-S", "Sutron", "", "", "DCP");
        //        e.AddequipmentmodelRow(2, "MCF-A", "FTX", "TX312", "", "DCP");
        //        e.AddequipmentmodelRow(3, "MCF-D", "Design Analysis", "", "", "DCP");
        //        e.AddequipmentmodelRow(4, "MCF-V", "Vitel", "", "", "DCP");
        //        e.AddequipmentmodelRow(5, "CR1000", "CSV", "", "", "TransportMedium");



        //        ep.AddequipmentpropertyRow(1, "DataOrder", "D");
        //        ep.AddequipmentpropertyRow(2, "DataOrder", "A");
        //        ep.AddequipmentpropertyRow(3, "DataOrder", "D");
        //        ep.AddequipmentpropertyRow(4, "DataOrder", "D");
        //        ep.AddequipmentpropertyRow(5, "DataOrder", "A");


        //}

        public static void UpdateServer(PostgreSQL svr, DecodesDataSet decodes)
        {
            foreach (var tableName in tableNames)
            {
                Console.Write("Saving " + tableName);
                var c = svr.SaveTable(decodes.Tables[tableName]);
                Console.WriteLine(" " + c.ToString() + " records");
            }
        }
Example #21
0
 public McfDecodesConverter(PostgreSQL svr, McfDataSet mcf, DecodesDataSet decodes,
                            string[] siteList)
 {
     m_siteList   = siteList;
     this.svr     = svr;
     this.mcf     = mcf;
     this.decodes = decodes;
     m_converter  = new UnitConversion(mcf, decodes, svr);
 }
Example #22
0
 public static TimeSeriesDatabase GetTimeSeriesDatabase()
 {
     if (s_db == null)
     {
         var svr = new PostgreSQL(Startup.ApiConnectionString);
         var db  = new TimeSeriesDatabase(svr, true);
         s_db = db;
     }
     return(s_db);
 }
Example #23
0
        /// <summary>
        /// Gets size of database of current server
        /// </summary>
        /// <returns>size of database in GB</returns>
        public float getDataBaseSizeInGb()
        {
            this.connectionString = "Host=" + this.Host +
                                    ";Username="******";Password="******";Database=" + this.Database;

            PostgreSQL database = new PostgreSQL(this.connectionString);

            return(database.getDataBaseSizeInGb());
        }
Example #24
0
 private static void Cleanup()
 {
     try
     {
         HydrometTools.ssh.Utility.Close();
         PostgreSQL.ClearAllPools();
     }
     catch (Exception)
     {
     }
 }
Example #25
0
        ///// <summary>
        ///// Used to create DataSET.
        ///// </summary>
        ///// <param name="svr"></param>
        ///// <returns></returns>
        //public static DecodesDataSet GetEmptyDataSet(PostgreSQL svr)
        //{
        //    var ds = new DecodesDataSet();

        //    for (int i = 0; i < tableNames.Length; i++)
        //    {
        //        string sql = "select * from " + tableNames[i] + " where 2=1";
        //        svr.FillTable(ds.Tables[tableNames[i]], sql);
        //    }

        //    return ds;
        //}

        public static void CreateDecodesXSD(PostgreSQL svr, string outputFilename)
        {
            DataSet ds = new DataSet("DecodesDataSet");

            foreach (var tableName in tableNames)
            {
                string sql = "select * from " + tableName + " where 1=2";
                ds.Tables.Add(svr.Table(tableName, sql));
            }

            ds.WriteXmlSchema(outputFilename);
        }
Example #26
0
        public static void GenerateDataSet(string filename, PostgreSQL svr)
        {
            DataSet ds = new DataSet();

            foreach (var tn in svr.TableNames())
            {
                var t = svr.Table(tn, "select * from " + tn + " where 1=2");
                ds.Tables.Add(t);
            }

            ds.WriteXmlSchema(filename);
        }
Example #27
0
        public object CreateFeedback(FeedBack feed)
        {
            string token = null;
            //获取请求
            var request = HttpContext.Current.Request;
            //声明响应
            ResultMsg <User>    resultmsg = new ResultMsg <User>();
            HttpResponseMessage response  = new HttpResponseMessage();

            if (feed == null)//判断输入的数据格式是否正确
            {
                resultmsg.status = false;
                resultmsg.msg    = "输入的数据格式不正确,请检查后重新输入!";
                resultmsg.data   = null;
                token            = request.Headers["Token"];
            }
            else
            {
                PostgreSQL.OpenCon();
                var tans = PostgreSQL.BeginTransaction();
                try
                {
                    string str  = "insert into tb_feedback (userid ,suggestion ,url)values(@userid,@suggestion,@url) ; ";
                    var    para = new DbParameter[3];
                    para[0] = PostgreSQL.NewParameter("@suggestion", feed.suggestion);
                    para[1] = PostgreSQL.NewParameter("@url", feed.url);
                    para[2] = PostgreSQL.NewParameter("@userid", feed.userid);
                    int num = PostgreSQL.ExecuteNoneQuery(str, tans, para);
                    PostgreSQL.CommitTransaction(tans);
                    //返回信息
                    resultmsg.status = true;
                    resultmsg.msg    = "意见反馈成功!";
                    resultmsg.data   = null;
                    token            = request.Headers["Token"];
                }
                catch (Exception ex)
                {
                    PostgreSQL.RollbackTransaction(tans);
                    //返回信息
                    resultmsg.status = false;
                    resultmsg.msg    = "[ERROR] 数据库操作出现异常:" + ex.Message;
                    resultmsg.data   = null;
                    token            = request.Headers["Token"];
                }
                PostgreSQL.CloseCon();
            }
            //添加响应头
            var resultObj = JsonConvert.SerializeObject(resultmsg, Formatting.Indented);

            response.Headers.Add("Token", token);
            response.Content = new StringContent(resultObj);
            return(response);
        }
Example #28
0
        private static void SetExpectedLength()
        {
            CsvFile csv = new CsvFile(@"c:\temp\site.csv", CsvFile.FieldTypes.AllText);
            var     cs  = PostgreSQL.CreateADConnectionString("opendcs", "hydromet_opendcs");

            PostgreSQL svr = new PostgreSQL(cs);

            var platform         = svr.Table("platform");
            var platformproperty = svr.Table("platformproperty");

            System.Console.WriteLine(platform.Rows.Count);
            System.Console.WriteLine(platformproperty.Rows.Count);


            for (int i = 0; i < csv.Rows.Count; i++)
            {
                var row          = csv.Rows[i];
                var site         = row["site"].ToString();
                var nessid       = row["NESSID"].ToString();
                var expectLength = row["STMSGLEN"].ToString();

                if (nessid.Trim() == "0" || nessid.Trim().Length < 5)
                {
                    continue;
                }
                // find platform with platformdesignator= site

                var rows = platform.Select("platformdesignator='" + site + "'");
                if (rows.Length != 1)
                {
                    System.Console.WriteLine("skipping " + site);
                    continue;
                }

                int id = Convert.ToInt32(rows[0]["id"]);

                var x = platformproperty.Select("platformid = " + id + "and prop_name='expectLength' ");

                Console.WriteLine(site + " " + expectLength);
                if (x.Length == 1)
                {// update existing
                    x[0]["prop_value"] = expectLength;
                }
                else
                {// add new row
                    platformproperty.Rows.Add(id, "expectLength", expectLength);
                }
            }
            var j = svr.SaveTable(platformproperty);

            Console.WriteLine(j + " rows saved");
        }
Example #29
0
        public static PostgreSQL GetServer(string dbname)
        {
            var pw = GetPassword();

            if (pw == "")
            {
                throw new Exception("Error: the password is blank. Please set this in the settings tab");
            }

            BasicDBServer svr = PostgreSQL.GetPostgresServer(dbname, password: pw);

            return(svr as PostgreSQL);
        }
Example #30
0
        static void Main(string[] args)
        {
            var fn = @"C:\temp\pn.pdb";
            //var svr_vm = MySqlServer.GetMySqlServer("vm", "timeseries");
            var svr_vm = new SQLiteServer(fn);

            if (svr_vm.TableExists("seriescatalog"))
            {
                svr_vm.RunSqlCommand("truncate seriescatalog");
            }
            if (svr_vm.TableExists("sitescatalog"))
            {
                svr_vm.RunSqlCommand("truncate sitecatalog");
            }

            var db_vm    = new TimeSeriesDatabase(svr_vm, Reclamation.TimeSeries.Parser.LookupOption.TableName);
            var sites_vm = db_vm.GetSiteCatalog();

            var svr   = PostgreSQL.GetPostgresServer("timeseries", "lrgs1");
            var db    = new TimeSeriesDatabase(svr, Reclamation.TimeSeries.Parser.LookupOption.TableName);
            var sites = db.GetSiteCatalog();

            string program = "agrimet";
            var    sc      = db.GetSeriesCatalog("timeinterval='Daily'", "program:" + program);
            var    sc_vm   = db_vm.GetSeriesCatalog();

            LoadDailyUsbrCatalog(sc, sc_vm, program);
            //db_vm.Server.SaveTable(sc_vm);

            LoadUpperSnakeHydromet(sc_vm);

            db_vm.Server.SaveTable(sc_vm);
            // install all sites that are referenced in series catalog

            var tmp = db_vm.Server.Table("tmp", "select distinct siteid from seriescatalog");

            for (int i = 0; i < tmp.Rows.Count; i++)
            {
                string siteid = tmp.Rows[i]["siteid"].ToString();
                var    rows   = sites.Select("siteid='" + siteid + "'");
                if (rows.Length > 0)
                {
                    var newRow = sites_vm.NewsitecatalogRow();
                    newRow.ItemArray = rows[0].ItemArray;
                    sites_vm.Rows.Add(newRow);
                }
            }

            db_vm.Server.SaveTable(sites_vm);
        }
Example #31
0
        public alarm_definitionDataTable GetAlarmDefinition(string siteid, string parameter)
        {
            var alarm_definition = new AlarmDataSet.alarm_definitionDataTable();

            siteid    = PostgreSQL.SafeSqlLikeClauseLiteral(siteid);
            parameter = SqlServer.SafeSqlLikeClauseLiteral(parameter);
            var sql = "select * from alarm_definition where siteid='" + siteid + "'"
                      + " and parameter ='" + parameter + "'";

            m_server.FillTable(alarm_definition, sql);

            alarm_definition.idColumn.AutoIncrementSeed = m_server.NextID("alarm_definition", "id");
            return(alarm_definition);
        }