Example #1
0
        //update Delegation
        public static DelegationModel UpdateDelegation(DelegationModel dm, out String error)
        {
            error = "";
            // declare and initialize new LUSSISEntities to perform update
            LUSSISEntities entities = new LUSSISEntities();
            delegation     d        = new delegation();

            try
            {
                // finding the delegation object using delegation API model
                d = entities.delegations.Where(p => p.delid == dm.Delid).First <delegation>();

                // transfering data from API model to DB Model
                d.startdate  = dm.Startdate;
                d.enddate    = dm.Enddate;
                d.userid     = dm.Userid;
                d.active     = dm.Active;
                d.assignedby = dm.AssignedbyId;

                // saving the update
                entities.SaveChanges();

                // return the updated model
                dm = CovertDBDelegationtoAPIUser(d);
            }
            catch (NullReferenceException)
            {
                error = ConError.Status.NOTFOUND;
            }
            catch (Exception e)
            {
                error = e.Message;
            }
            return(dm);
        }
Example #2
0
        public void InsertMars()
        {
            JObject jo;
            JArray  ja;

            for (int sol_para = 1; sol_para <= 1850; sol_para++)
            {
                //string sql_str = "delete from blue.mars where sol = '" + sol_para + "'";
                //msql.Set(sql_str);
                string url = "https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=" + sol_para.ToString() + "&api_key=icBzEa0TOhgaeCRaTrFO3nh9uxSChoBUEXAB3MgH";
                string str = GetUrlResponse(url);
                jo = JObject.Parse(str);
                ja = JArray.Parse(jo["photos"].ToString());
                foreach (JObject item in ja)
                {
                    string earth_date = item["earth_date"].ToString();
                    string sol        = item["sol"].ToString();
                    string img_id     = item["id"].ToString();
                    string img_name   = item["camera"]["full_name"].ToString();
                    string img_src    = item["img_src"].ToString();
                    string sql        = "insert into blue.mars " +
                                        "(earth_date,sol,img_id,img_name,img_src,update_time) " +
                                        "values " +
                                        "('" + earth_date + "','" + sol + "','" + img_id + "','" + img_name + "','" + img_src + "',CURRENT_DATE)";
                    msql.Set(sql);
                }
                delegation d_a = new delegation(GApp_Add);
                lb_Status.Invoke(d_a, sol_para.ToString());
            }
            MessageBox.Show("完成!");
        }
Example #3
0
        private static DelegationModel CovertDBDelegationtoAPIUser(delegation delegation)
        {
            DelegationModel dgm = new DelegationModel(delegation.delid, delegation.startdate,
                                                      delegation.enddate, delegation.userid, delegation.user.username, delegation.user.role,
                                                      delegation.user.department.deptname,
                                                      delegation.active, delegation.assignedby, delegation.user1.username, delegation.user1.role,
                                                      delegation.user1.department.deptname);

            return(dgm);
        }
Example #4
0
        //search the previous delegation with userlist
        public static DelegationModel SearchPreviousDelegation(int deptid, out string error)
        {
            error = "";
            LUSSISEntities    entities = new LUSSISEntities();
            List <department> dept     = new List <department>();
            List <user>       ums      = new List <user>();
            List <UserModel>  urm      = new List <UserModel>();

            try
            {
                ums = entities.users.Where(p => p.deptid == deptid && p.role != ConUser.Role.HOD).ToList <user>();
                foreach (user u in ums)
                {
                    urm.Add(UserRepo.CovertDBUsertoAPIUser(u));
                }
            }
            catch (NullReferenceException)
            {
                error = ConError.Status.NOTFOUND;
            }
            catch (Exception e)
            {
                error = e.Message;
            }


            delegation      d    = new delegation();
            DelegationModel ndel = new DelegationModel();

            try
            {
                foreach (UserModel um in urm)
                {
                    List <DelegationModel> delee = GetDelegationByUserId(um.Userid, out error);

                    foreach (DelegationModel dm in delee)
                    {
                        if (dm.Active == ConDelegation.Active.ACTIVE)
                        {
                            ndel = dm;
                        }
                    }
                }
            }
            catch (NullReferenceException)
            {
                error = ConError.Status.NOTFOUND;
            }
            catch (Exception e)
            {
                error = e.Message;
            }
            return(ndel);
        }
Example #5
0
        //cancel delegation

        public static DelegationModel CancelDelegation(DelegationModel dm, out String error)
        {
            error = "";
            // declare and initialize new LUSSISEntities to perform update
            LUSSISEntities entities = new LUSSISEntities();
            delegation     d        = new delegation();

            try
            {
                // finding the delegation object using delegation API model
                d = entities.delegations.Where(p => p.delid == dm.Delid).First <delegation>();


                d.active = ConDelegation.Active.INACTIVE;

                // saving the update
                entities.SaveChanges();

                UserRepo.Canceldelegateuser(dm.Userid);

                // return the updated model
                dm = GetDelegationByDelegationID(d.delid, out error);


                user us = entities.users.Where(p => p.userid == dm.Userid).FirstOrDefault();

                NotificationModel nom = new NotificationModel();
                nom.Deptid   = us.deptid;
                nom.Role     = ConUser.Role.EMPLOYEEREP;
                nom.Title    = "Authority Cancellation";
                nom.NotiType = ConNotification.NotiType.DelegationAssigned;
                nom.ResID    = dm.Userid;
                nom.Remark   = us.fullname + " has been removed as a Temp Head of Department!";
                nom          = NotificationRepo.CreatNotification(nom, out error);

                nom.Deptid   = us.deptid;
                nom.Role     = ConUser.Role.TEMPHOD;
                nom.Title    = "Authority Cancellation";
                nom.NotiType = ConNotification.NotiType.DelegationAssigned;
                nom.ResID    = dm.Userid;
                nom.Remark   = us.fullname + " has been removed as a Temp Head of Department!";
                nom          = NotificationRepo.CreatNotification(nom, out error);
            }
            catch (NullReferenceException)
            {
                error = ConError.Status.NOTFOUND;
            }
            catch (Exception e)
            {
                error = e.Message;
            }
            return(dm);
        }
        public void RefreshNCOV()
        {
            while (true)
            {
                NCOV();

                int        delay = new Random().Next(500, 5000);
                delegation d_a   = new delegation(GApp_Add);
                lb_Status.Invoke(d_a, "下次更新肺炎数据将在" + delay.ToString() + "秒后");
                Thread.Sleep(delay * 1000);
            }
        }
        public void RefreshTuring()
        {
            string com = "update blue.turing set state = '1'";

            msql.I_D_U(com);
            delegation d_c = new delegation(GApp_Clear);

            lb_Status.Invoke(d_c, "");
            delegation d_a = new delegation(GApp_Add);

            lb_Status.Invoke(d_a, "更新图灵数据");
        }
        public void RefreshLC()
        {
            while (true)
            {
                LC();

                int        delay = new Random().Next(500, 1800);
                delegation d_a   = new delegation(GApp_Add);
                lb_Status.Invoke(d_a, "LC的下次重新部署将在" + delay.ToString() + "秒后");
                Thread.Sleep(delay * 1000);
            }
        }
        public void RefreshMars()
        {
            JObject jo;
            JArray  ja;

            string url = "https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?earth_date=2012-08-07&api_key=icBzEa0TOhgaeCRaTrFO3nh9uxSChoBUEXAB3MgH";
            string str = GetUrlResponse(url);

            jo = JObject.Parse(str);
            ja = JArray.Parse(jo["photos"].ToString());
            jo = (JObject)ja[0];
            jo = JObject.Parse(jo["rover"].ToString());
            string Max = jo["max_date"].ToString() + "|" + jo["max_sol"].ToString();
            string sql = "delete from blue.marsmax;";

            sql = sql + "insert into blue.marsmax(update_time,value) values (CURRENT_DATE,'" + Max + "')";
            msql.I_D_U(sql);

            url = "https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?earth_date=" + jo["max_date"].ToString() + "&api_key=icBzEa0TOhgaeCRaTrFO3nh9uxSChoBUEXAB3MgH";
            str = GetUrlResponse(url);
            jo  = JObject.Parse(str);
            ja  = JArray.Parse(jo["photos"].ToString());
            foreach (JObject item in ja)
            {
                string earth_date = item["earth_date"].ToString();
                string sol        = item["sol"].ToString();
                string img_id     = item["id"].ToString();
                string img_name   = item["camera"]["full_name"].ToString();
                string img_src    = item["img_src"].ToString();
                sql = "delete from blue.mars where img_id = " + img_id + ";";
                sql = sql + "insert into blue.mars " +
                      "(earth_date,sol,img_id,img_name,img_src,update_time) " +
                      "values " +
                      "('" + earth_date + "','" + sol + "','" + img_id + "','" + img_name + "','" + img_src + "',CURRENT_DATE)";
                msql.I_D_U(sql);
            }
            delegation d_c = new delegation(GApp_Clear);

            lb_Status.Invoke(d_c, "");
            delegation d_a = new delegation(GApp_Add);

            lb_Status.Invoke(d_a, "更新火星数据");
        }
Example #10
0
        /// <summary>
        /// 获取20秒的原始数据
        /// </summary>
        private void Get40()
        {
            int    i   = 0;
            int    j   = 0;
            string str = "";

            for (j = 0; j < StockDT.Rows.Count + 600; j += 600)
            {
                string url = "http://hq.sinajs.cn/list=";
                if (j > StockDT.Rows.Count)
                {
                    j = StockDT.Rows.Count;
                }
                if (j > 0)
                {
                    for (; i < j; i++)
                    {
                        url = url + StockDT.Rows[i][0] + ",";
                    }
                    url = url.Substring(0, url.Length - 1);
                    //创建请求
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    //GET请求
                    request.Method           = "get";
                    request.ContentType      = "text/html";
                    request.ReadWriteTimeout = 1000;
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream          s        = response.GetResponseStream();
                    StreamReader    sr       = new StreamReader(s, Encoding.GetEncoding("gb2312"));
                    //返回内容
                    str = str + sr.ReadToEnd();
                }
            }
            string       filename_p = DateTime.Now.Ticks + "_40.txt";
            StreamWriter sw         = new StreamWriter(Path + filename_p, false);

            sw.WriteLine(str);
            sw.Close();
            delegation d_a = new delegation(GApp_Add);

            lb_Now.Invoke(d_a, filename_p + "写入成功。");
        }
        public void LC()
        {
            delegation d_a = new delegation(GApp_Add);

            if (DateTime.Now.Hour < 7)
            {
                lb_Status.Invoke(d_a, "零点到七点不提醒");
                return;
            }

            String url    = "https://leancloud.cn/1.1/engine/groups/web/production/version?gitTag=master&token=cHU2xZZEUggbOJgyK7KrbTpeiGGwMz047Er12F8OztWq5FJptuofM85keflgCt0f";
            var    client = new RestClient(url);

            client.Timeout = 5000;
            var           request  = new RestRequest(Method.POST);
            IRestResponse response = client.Execute(request);

            lb_Status.Invoke(d_a, response.Content);
            lb_Status.Invoke(d_a, "LC部署完成");
        }
Example #12
0
        public static DelegationModel GetDelegationByDelegationID(int delid, out string error)
        {
            error = "";

            delegation      dele = new delegation();
            DelegationModel dm   = new DelegationModel();

            try
            {
                dele = entities.delegations.Where(p => p.delid == delid).FirstOrDefault <delegation>();
                dm   = CovertDBDelegationtoAPIUser(dele);
            }
            catch (NullReferenceException)
            {
                error = ConError.Status.NOTFOUND;
            }
            catch (Exception e)
            {
                error = e.Message;
            }
            return(dm);
        }
Example #13
0
 private void ToDB()
 {
     foreach (string path in FileList)
     {
         StreamReader sr    = new StreamReader(path);
         string       code  = path.Substring(path.LastIndexOf('\\') + 1, path.Length - path.LastIndexOf('\\') - 5);
         string       Table = path.Substring(0, path.LastIndexOf('\\'));
         Table = Table.Substring(Table.LastIndexOf('\\') + 1, 4);
         if (code.StartsWith("SH6") || code.StartsWith("SZ000") || code.StartsWith("SZ002") || code.StartsWith("SZ300"))
         {
             string com  = "INSERT INTO stock." + Table + "(code,date,time,open,close) values";
             string line = "";
             while ((line = sr.ReadLine()) != null)
             {
                 string[] str   = line.Split(',');
                 string   date  = str[0];
                 string   time  = str[1];
                 string   open  = str[2];
                 string   close = str[5];
                 com = com + "('" + code + "','" + date + "','" + time + "','" + open + "','" + close + "'),";
             }
             com = com.Substring(0, com.Length - 1);
             MySqlConnection myConn = new MySqlConnection("server=localhost;user id=root; password=MySQL; database=" + "stock" + "; pooling=false;port=3306");
             MySqlCommand    cmd;
             cmd             = myConn.CreateCommand(); //sql命令对象,表示要对sql数据库执行一个sql语句
             cmd.CommandText = com;
             myConn.Open();                            //打开连接
             cmd.ExecuteNonQuery();                    //执行不是查询的sql语句
             myConn.Close();
             delegation d_a = new delegation(GApp_Add);
             lb_Now.Invoke(d_a, path);
         }
         sr.Close();
         File.Delete(path);
     }
     MessageBox.Show("完成!");
 }
        public void NCOV()
        {
            delegation d_a          = new delegation(GApp_Add);
            string     fileName     = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + new Random().Next().ToString() + ".json";
            string     url          = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx8898a07816bc5f05&secret=bfb3101627c7eff4db1b7f01e566172a";
            string     str          = GetUrlResponse(url);
            string     access_token = JObject.Parse(str)["access_token"].ToString();

            lb_Status.Invoke(d_a, "更新肺炎数据:access_token获取成功");
            url = "https://rl.inews.qq.com/taf/travelFront";
            str = GetUrlResponse_2nd(url);
            JArray ja     = JArray.Parse(JObject.Parse(str)["data"]["list"].ToString());
            JArray jaList = new JArray();

            foreach (JObject item in ja)
            {
                JObject temp = new JObject();
                temp["t_date"]  = item["date"];
                temp["t_start"] = item["start"].ToString() == "" ? "数据缺失" : item["start"];
                temp["t_end"]   = item["end"].ToString() == "" ? "数据缺失" : item["end"];
                switch (item["type"].ToString())
                {
                case "1":
                    temp["t_type"] = "飞机";
                    break;

                case "2":
                    temp["t_type"] = "火车";
                    break;

                case "3":
                    temp["t_type"] = "地铁";
                    break;

                case "4":
                    temp["t_type"] = "长途客车";
                    break;

                case "5":
                    temp["t_type"] = "公交车";
                    break;

                case "6":
                    temp["t_type"] = "出租车";
                    break;

                case "7":
                    temp["t_type"] = "轮船";
                    break;

                case "8":
                    temp["t_type"] = "其他公共场所";
                    break;
                }
                temp["t_no"]        = item["no"].ToString() == "" ? "数据缺失" : item["no"];
                temp["t_memo"]      = item["memo"].ToString() == "" ? "无" : item["memo"];
                temp["t_no_sub"]    = item["no_sub"].ToString() == "" ? "数据缺失" : item["no_sub"];
                temp["t_pos_start"] = item["pos_start"].ToString() == "" ? "数据缺失" : item["pos_start"];
                temp["t_pos_end"]   = item["pos_end"].ToString() == "" ? "数据缺失" : item["pos_end"];
                temp["source"]      = item["source"].ToString() == "" ? "数据缺失" : item["source"];
                temp["who"]         = item["who"].ToString() == "" ? "数据缺失" : item["who"];
                jaList.Add(temp);
            }
            string text = jaList.ToString().Replace("},", "}").Substring(1, jaList.ToString().Replace("},", "}").Length - 2);

            System.IO.File.WriteAllText(fileName, text);
            lb_Status.Invoke(d_a, "更新肺炎数据:爬取文件成功");
            Thread.Sleep(5000);

            //上传文件 第一步
            url = "https://api.weixin.qq.com/tcb/uploadfile?access_token=" + access_token;
            var client = new RestClient(url);

            client.Timeout = 5000;
            var request = new RestRequest(Method.POST);

            request.AddParameter("application/json", "{\"env\": \"kaka-ncov\",\"path\": \"" + fileName + "\"}", ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);

            lb_Status.Invoke(d_a, "更新肺炎数据:上传文件 1/3");
            //上传文件  第二步
            JObject res = JObject.Parse(response.Content);

            url = res["url"].ToString();
            string token         = res["token"].ToString();
            string authorization = res["authorization"].ToString();
            string file_id       = res["file_id"].ToString();
            string cos_file_id   = res["cos_file_id"].ToString();

            lb_Status.Invoke(d_a, "更新肺炎数据:上传文件 2/3");

            //上传文件  第三步
            client         = new RestClient(url);
            client.Timeout = 5000;
            request        = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "multipart/form-data");
            request.AlwaysMultipartFormData = true;
            request.AddParameter("key", fileName);
            request.AddParameter("Signature", authorization);
            request.AddParameter("x-cos-security-token", token);
            request.AddParameter("x-cos-meta-fileid", cos_file_id);
            request.AddFile("file", fileName);
            response = client.Execute(request);
            lb_Status.Invoke(d_a, "更新肺炎数据:上传文件 3/3");
            Thread.Sleep(5000);

            lb_Status.Invoke(d_a, "上传文件已经完成,等待3分钟");
            Thread.Sleep(180000);

            url            = "https://api.weixin.qq.com/tcb/databasecollectiondelete?access_token=" + access_token;
            client         = new RestClient(url);
            client.Timeout = 5000;
            request        = new RestRequest(Method.POST);
            request.AddParameter("application/json", "{\"env\": \"kaka-ncov\",\"collection_name\": \"nCoV\"}", ParameterType.RequestBody);
            response = client.Execute(request);
            lb_Status.Invoke(d_a, "更新肺炎数据:drop nCoV成功");
            Thread.Sleep(5000);

            url            = "https://api.weixin.qq.com/tcb/databasecollectionadd?access_token=" + access_token;
            client         = new RestClient(url);
            client.Timeout = 5000;
            request        = new RestRequest(Method.POST);
            request.AddParameter("application/json", "{\"env\": \"kaka-ncov\",\"collection_name\": \"nCoV\"}", ParameterType.RequestBody);
            response = client.Execute(request);
            lb_Status.Invoke(d_a, "更新肺炎数据:create nCoV成功");
            Thread.Sleep(5000);

            url            = "https://api.weixin.qq.com/tcb/databasemigrateimport?access_token=" + access_token;
            client         = new RestClient(url);
            client.Timeout = 5000;
            request        = new RestRequest(Method.POST);
            request.AddParameter("application/json", "{\"env\": \"kaka-ncov\",\"collection_name\": \"nCoV\",\"file_path\": \"" + fileName + "\",\"file_type\": 1,\"stop_on_error\": false,\"conflict_mode\": 1}", ParameterType.RequestBody);
            response = client.Execute(request);
            lb_Status.Invoke(d_a, "更新肺炎数据:更新数据成功");
            Thread.Sleep(5000);

            url            = "https://api.weixin.qq.com/tcb/databaseupdate?access_token=" + access_token;
            client         = new RestClient(url);
            client.Timeout = 5000;
            request        = new RestRequest(Method.POST);
            request.AddParameter("application/json", "{\"env\": \"kaka-ncov\",\"query\": \"" + "db.collection('show').doc('show').update({data:{update : '" + DateTime.Now.ToString("MM-dd HH:mm") + "'}})" + "\"}", ParameterType.RequestBody);
            response = client.Execute(request);
            lb_Status.Invoke(d_a, "更新肺炎数据:更新日期成功");
            Thread.Sleep(5000);

            lb_Status.Invoke(d_a, "更新肺炎数据:所有更新完成");
        }
Example #15
0
        //create delegation
        public static DelegationModel CreateDelegation(DelegationModel dele, out string error)
        {
            error = "";
            LUSSISEntities  entities = new LUSSISEntities();
            delegation      d        = new delegation();
            DelegationModel ndel     = new DelegationModel();

            try
            {
                DepartmentModel  dep      = DepartmentRepo.GetDepartmentByUserid(dele.Userid, out error);
                List <UserModel> userlist = UserRepo.GetUserByDeptid(dep.Deptid, out error);
                foreach (UserModel u in userlist)
                {
                    List <DelegationModel> delelist = GetDelegationByUserId(u.Userid, out error);
                    foreach (DelegationModel deleg in delelist)
                    {
                        delegation del = entities.delegations.Where(p => p.delid == deleg.Delid).FirstOrDefault <delegation>();
                        del.active = ConDelegation.Active.INACTIVE;
                        if (u.Role != ConUser.Role.DEPARTMENTREP)
                        {
                            UserRepo.Canceldelegateuser(u.Userid);
                        }
                        entities.SaveChanges();
                    }
                }
                d.startdate  = dele.Startdate;
                d.enddate    = dele.Enddate;
                d.userid     = dele.Userid;
                d.active     = ConDelegation.Active.ACTIVE;
                d.assignedby = dele.AssignedbyId;
                d            = entities.delegations.Add(d);
                entities.SaveChanges();

                dele = GetDelegationByDelegationID(d.delid, out error);


                user us = entities.users.Where(p => p.userid == dele.Userid).FirstOrDefault();

                NotificationModel nom = new NotificationModel();
                nom.Deptid   = us.deptid;
                nom.Role     = ConUser.Role.TEMPHOD;
                nom.Title    = "New Authority";
                nom.NotiType = ConNotification.NotiType.DelegationAssigned;
                nom.ResID    = dele.Userid;
                nom.Remark   = us.fullname + " has been assigned as a Temp HOD from " + dele.Startdate.Value.ToShortDateString() + " to " + dele.Enddate.Value.ToShortDateString();
                nom          = NotificationRepo.CreatNotification(nom, out error);


                nom.Deptid   = us.deptid;
                nom.Role     = ConUser.Role.EMPLOYEEREP;
                nom.Title    = "New Authority";
                nom.NotiType = ConNotification.NotiType.DelegationAssigned;
                nom.ResID    = dele.Userid;
                nom.Remark   = us.fullname + " has been assigned as a Temp HOD from " + dele.Startdate.Value.ToShortDateString() + " to " + dele.Enddate.Value.ToShortDateString();
                nom          = NotificationRepo.CreatNotification(nom, out error);
            }
            catch (NullReferenceException)
            {
                error = ConError.Status.NOTFOUND;
            }
            catch (Exception e)
            {
                error = e.Message;
            }
            return(dele);
        }
Example #16
0
        /// <summary>
        /// 把文件里的数据读入数据库
        /// </summary>
        private void ToDB()
        {
            delegation d_a      = new delegation(GApp_Add);
            long       FileTime = 0;

            string[] FileArr = System.IO.Directory.GetFiles(Path);
            while (FileArr.Length > 0)
            {
                //对FileArr 重新赋值
                FileArr = System.IO.Directory.GetFiles(Path);
                //给一次机会
                if (FileArr.Length == 0)
                {
                    Thread.Sleep(120000);
                    continue;
                }
                Array.Sort(FileArr);
                //如果第一个文件的创建时间小于两分钟,那么有可能还没写好,等待两分钟
                FileInfo fi = new FileInfo(FileArr[0]);
                if (DateTime.Now.Subtract(fi.CreationTime).TotalSeconds < 120)
                {
                    Thread.Sleep(120000);
                }
                //如果时间小于10秒
                if (fi.CreationTime.Ticks - FileTime < 100000000)
                {
                    FileTime = fi.CreationTime.Ticks;
                }
                else
                {
                    FileTime = fi.CreationTime.Ticks;
                    //用 ; 对股票进行拆分
                    StreamReader sr          = new StreamReader(FileArr[0]);
                    string[]     FileContent = sr.ReadToEnd().Split(';');
                    string       com         = "INSERT INTO stock.0000 (code,date,time,open,close) values";
                    foreach (string FileLine in FileContent)
                    {
                        //用 , 对股票字段进行拆分
                        string[] StockContent = FileLine.Split(',');
                        if (StockContent.Length == 33)
                        {
                            string code  = StockContent[0].Substring(StockContent[0].LastIndexOf("_") + 1, 8);
                            string date  = StockContent[30];
                            string time  = StockContent[31];
                            string open  = StockContent[2];
                            string close = StockContent[3];
                            com = com + "('" + code + "','" + date + "','" + time + "','" + open + "','" + close + "'),";
                        }
                    }
                    com = com.Substring(0, com.Length - 1);
                    ms.I_D_U(com);
                    sr.Close();
                }
                File.Delete(FileArr[0]);
                string filename_p = FileArr[0].Substring(FileArr[0].LastIndexOf('\\') + 1, FileArr[0].Length - FileArr[0].LastIndexOf('\\') - 1);
                lb_Now.Invoke(d_a, filename_p + "读取成功。");
                //对FileArr 重新赋值
                FileArr = System.IO.Directory.GetFiles(Path);
            }
            lb_Now.Invoke(d_a, L + "入库完成。");
        }
        public void RefreshFund()
        {
            string code;          /*基金代码*/
            string name;          /*基金简称*/
            string newnet;        /*最新净值*/
            string totalnet;      /*累计净值*/
            string dayincrease;   /*日增长值*/
            string daygrowrate;   /*日增长率%*/
            string weekgrowrate;  /*周增长率%*/
            string monthgrowrate; /*月增长率%*/
            string time;          /*最新净值时间*/

            DateTime updatatime;  //更新时间


            delegation d_c = new delegation(GApp_Clear);

            lb_Status.Invoke(d_c, "");
            string appkey = "c5084b27fed7043fd49e98a989631c15"; //配置您申请的appkey
            string url    = "http://web.juhe.cn:8080/fund/netdata/all";

            var parameters = new Dictionary <string, string>();

            parameters.Add("key", appkey);//你申请的key
            string result = sendPost(url, parameters, "get");

            Xfrog.Net.JsonObject jo = new Xfrog.Net.JsonObject(result);
            String errorCode        = jo["error_code"].Value;

            if (errorCode == "0")
            {
                string  strFund = JArray.Parse(jo["result"].ToString())[0].ToString();
                JObject jor     = JObject.Parse(strFund);
                msql.I_D_U("delete from blue.fundnet");
                for (int i = 1; i < 1000000; i++)
                {
                    try
                    {
                        string  strRow = jor[i.ToString()].ToString();
                        JObject _jor   = JObject.Parse(strRow);
                        code          = _jor["code"].ToString();
                        name          = _jor["name"].ToString();
                        newnet        = _jor["newnet"].ToString();        /*最新净值*/
                        totalnet      = _jor["totalnet"].ToString();      /*累计净值*/
                        dayincrease   = _jor["dayincrease"].ToString();   /*日增长值*/
                        daygrowrate   = _jor["daygrowrate"].ToString();   /*日增长率%*/
                        weekgrowrate  = _jor["weekgrowrate"].ToString();  /*周增长率%*/
                        monthgrowrate = _jor["monthgrowrate"].ToString(); /*月增长率%*/
                        time          = _jor["time"].ToString();          /*最新净值时间*/
                        updatatime    = DateTime.Now;
                        string com = "insert INTO blue.fundnet (code,name,newnet,totalnet,dayincrease,daygrowrate,weekgrowrate,monthgrowrate,time,updatatime)"
                                     + "values('" + code + "','" + name + "','" + newnet + "','" + totalnet + "','" + dayincrease + "','" + daygrowrate + "%','" + weekgrowrate + "%','" + monthgrowrate + "%','" + time + "','" + updatatime + "')";
                        msql.I_D_U(com);
                        delegation d_a = new delegation(GApp_Add);
                        lb_Status.Invoke(d_a, code + "-" + name);
                    }
                    catch
                    {
                        break;
                    }
                }
            }
            else
            {
                //如果错误代码不为0,说明出现了异常。这个时候应该给我提示。
                //给我发邮件或者别的咯
            }
        }
Example #18
0
        /// <summary>
        /// 量化分析沪深300
        /// </summary>
        private void Quant300()
        {
            delegation d_a = new delegation(GApp_Add);

            lb_Now.Invoke(d_a, "开始量化分析");
            string com = "";

            //Step 1 整理数据
            // SQL 去头去尾
            #region 整理数据
            lb_Now.Invoke(d_a, "开始整理数据");
            com = "delete from stock.0000 where time <= '09:30:00' or time >= '15:00:00'";
            ms.I_D_U(com);
            lb_Now.Invoke(d_a, "20%");
            com = "delete from stock.0000 where time >= '11:30:00' and time <= '13:00:00'";
            ms.I_D_U(com);
            lb_Now.Invoke(d_a, "40%");
            com = "update stock.0000 set fluctuation = close/open";
            ms.I_D_U(com);
            lb_Now.Invoke(d_a, "60%");
            com = "delete from stock.0000 where code in (select code from(select code,sum(fluctuation) as s from stock.0000 group by code) a where a.s = 720) ";
            ms.I_D_U(com);
            lb_Now.Invoke(d_a, "80%");
            com = "delete from stock.result ";
            ms.I_D_U(com);
            lb_Now.Invoke(d_a, "100%");
            lb_Now.Invoke(d_a, "整理数据完毕");
            #endregion
            //Step 2 计算拟合度
            #region 计算拟合度
            com = "select * from stock.300";
            DataTable dt_300 = new DataTable();
            dt_300 = ms.S(com);
            SimHash   sh      = new SimHash();
            DataTable dt_0000 = new DataTable();
            com     = "select fluctuation,code from stock.0000 order by time";
            dt_0000 = ms.S(com);
            foreach (DataRow dr_300 in dt_300.Rows)
            {
                DataRow[] drxArr = dt_0000.Select("code = '" + dr_300[1] + "'");
                if (drxArr.Length == 0)
                {
                    continue;
                }
                string str_Ins = "Insert into stock.result (code,object,sim) values";
                foreach (DataRow dr_Trade in StockDT.Rows)
                {
                    DataTable dt_y   = new DataTable();
                    DataRow[] dryArr = dt_0000.Select("code = '" + dr_Trade[0] + "'");
                    double    f      = sh.Cosine(drxArr, dryArr);
                    string    temp   = "('" + dr_300[1] + "','" + dr_Trade[0] + "','" + f + "'),";
                    temp    = temp.Replace("非数字", "0");
                    str_Ins = str_Ins + temp;
                }
                str_Ins = str_Ins.Substring(0, str_Ins.Length - 1);
                try
                {
                    ms.I_D_U(str_Ins);
                }
                catch
                {
                    Thread.Sleep(5000);
                    try
                    {
                        Thread.Sleep(5000);
                        ms.I_D_U(str_Ins);
                    }
                    catch
                    {
                        Thread.Sleep(5000);
                        try
                        {
                            ms.I_D_U(str_Ins);
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
                lb_Now.Invoke(d_a, dr_300[1] + "量化完成");
            }
            lb_Now.Invoke(d_a, "计算拟合度完毕");
            #endregion
            //Step 2.5 下载图片
            #region  载图片
            string StockPicPath = "C:\\Blue\\StockPic\\";
            if (Directory.Exists(StockPicPath))
            {
                Directory.Delete(StockPicPath, true);
                Directory.CreateDirectory(StockPicPath);
            }
            else
            {
                Directory.CreateDirectory(StockPicPath);
            }
            if (!Directory.Exists(StockPicPath))
            {
                Directory.CreateDirectory(StockPicPath);
            }
            foreach (DataRow drDown in StockDT.Rows)
            {
                try
                {
                    WebRequest  request  = WebRequest.Create("http://image.sinajs.cn/newchart/min/n/" + drDown[0] + ".gif");
                    WebResponse response = request.GetResponse();
                    Stream      reader   = response.GetResponseStream();
                    FileStream  writer   = new FileStream(StockPicPath + drDown[0] + ".gif", FileMode.OpenOrCreate, FileAccess.Write);
                    byte[]      buff     = new byte[512];
                    int         c        = 0; //实际读取的字节数
                    while ((c = reader.Read(buff, 0, buff.Length)) > 0)
                    {
                        writer.Write(buff, 0, c);
                    }
                    writer.Close();
                    writer.Dispose();
                    reader.Close();
                    reader.Dispose();
                    response.Close();
                    lb_Now.Invoke(d_a, drDown[0] + "下载完成");
                }
                catch
                {
                }
            }
            lb_Now.Invoke(d_a, "下载完毕");
            #endregion
            //Step 3 HTML
            #region HTML

            if (!Directory.Exists(Pic))
            {
                Directory.CreateDirectory(Pic);
            }

            DataTable dt_result = new DataTable();
            foreach (DataRow dr_300 in dt_300.Rows)
            {
                try
                {
                    PicName   = dr_300[1].ToString();
                    dt_result = ms.S("select object from stock.result where code = '" + dr_300[1] + "' and object != '" + dr_300[1] + "' order by sim desc LIMIT 10");
                    string html = "";
                    html = html + "<html xmlns=http://www.w3.org/1999/xhtml>";
                    html = html + "<head>";
                    html = html + "<meta http-equiv=Content-Type content=text/html; charset=utf-8 />";
                    html = html + "<title>" + dr_300[1].ToString().Substring(2, 6) + "  " + dr_300[2] + "</title>";
                    html = html + "</head>";
                    html = html + "<body>";
                    html = html + "<h3>(如未显示图片,请点击页面底部的【原网页】)<h3>";
                    html = html + "<h2>更新时间为:" + DateTime.Now.ToString("yyyy-MM-dd") + "</h2>";
                    html = html + "<h1>请求的股票为:</h1>";
                    html = html + "<img " + ImageToBase64("C:\\Blue\\StockPic\\" + dr_300[1] + ".gif") + " width=100% height=600>";
                    if (dt_result.Rows.Count != 10)
                    {
                        html = html + "<h1>该股票为停牌股</h1>";
                    }
                    else
                    {
                        html = html + "<h1>涨跌幅相似度从大到小排序的前十只依次为:</h1>";
                        html = html + "<h2>(大家看蓝色线条,是不是长得挺像呢。)</h2>";
                        html = html + "<img " + ImageToBase64("C:\\Blue\\StockPic\\" + dt_result.Rows[0][0] + ".gif") + " width=100% height=600>";
                        html = html + "<br /><img " + ImageToBase64("C:\\Blue\\StockPic\\" + dt_result.Rows[1][0] + ".gif") + " width=100% height=600>";
                        html = html + "<br /><img " + ImageToBase64("C:\\Blue\\StockPic\\" + dt_result.Rows[2][0] + ".gif") + " width=100% height=600>";
                        html = html + "<br /><img " + ImageToBase64("C:\\Blue\\StockPic\\" + dt_result.Rows[3][0] + ".gif") + " width=100% height=600>";
                        html = html + "<br /><img " + ImageToBase64("C:\\Blue\\StockPic\\" + dt_result.Rows[4][0] + ".gif") + " width=100% height=600>";
                        html = html + "<br /><img " + ImageToBase64("C:\\Blue\\StockPic\\" + dt_result.Rows[5][0] + ".gif") + " width=100% height=600>";
                        html = html + "<br /><img " + ImageToBase64("C:\\Blue\\StockPic\\" + dt_result.Rows[6][0] + ".gif") + " width=100% height=600>";
                        html = html + "<br /><img " + ImageToBase64("C:\\Blue\\StockPic\\" + dt_result.Rows[7][0] + ".gif") + " width=100% height=600>";
                        html = html + "<br /><img " + ImageToBase64("C:\\Blue\\StockPic\\" + dt_result.Rows[8][0] + ".gif") + " width=100% height=600>";
                        html = html + "<br /><img " + ImageToBase64("C:\\Blue\\StockPic\\" + dt_result.Rows[9][0] + ".gif") + " width=100% height=600>";
                    }
                    html = html + "<br /><h2>本功能所载的资料、工具及材料只提供给阁下作查照之用,并非作为或被视为出售或购买或认购证券或其它金融票据的建议或研究观点。所采用的信息均来源于已公开的资料,我本人对这些信息的准确性及完整性不作任何保证。市场有风险,投资需谨慎。</h2>";
                    html = html + "</body>";
                    html = html + "</html>";
                    StreamWriter sw = new StreamWriter(Pic + PicName + ".html", false, Encoding.UTF8);
                    sw.WriteLine(html);
                    sw.Close();
                    lb_Now.Invoke(d_a, PicName + "HTML完成");
                }
                catch
                {
                }
            }
            lb_Now.Invoke(d_a, "HTML完毕");
            #endregion
            lb_Now.Invoke(d_a, "量化分析结束");
        }