Exemple #1
0
        public List <string> GetAll()
        {
            SQLControl sql = new SQLControl(estimateDatabaseString);

            sql.ExecQuery("SELECT JobNumber FROM EstimateHeader");

            if (sql.HasException())
            {
                throw new Exception("The JobNumberRepository was unable to populate the list of job numbers");
            }
            else if (sql.DBDT.Rows.Count == 0)
            {
                //MessageBox.Show("There doesn't appear to be a record for the system: " + systemName + " in Job Number: " + _jobNumber + ". This could be:  \n" +
                //    "1. Because of a mismatch in system names between the name contained in the estimate sheet and the name contained in the report. \n" +
                //    "2. Because a phase code was included on the CSV report that wasn't included in the original Estimate." );
                return(null);
            }
            else
            {
                List <string> jobNumberList = new List <string>();

                for (int i = 0; i < sql.DBDT.Rows.Count; i++)
                {
                    string jobNumber = sql.DBDT.Rows[i].ItemArray[0].ToString();
                    jobNumberList.Add(jobNumber);
                }

                return(jobNumberList);
            }
        }
Exemple #2
0
        /// <summary>
        /// Returns the 'Earned' (estimated) hours from [EstimateMain] for the provided phase code and system name.
        /// </summary>
        /// <remarks>
        /// Connects to the "BudgetVSTO" database.
        /// </remarks>
        /// <param name="phaseCode"></param>
        /// <returns></returns>
        public double GetEarnedHours(string systemName, string phaseCode)
        {
            if (ValidateSystemName(systemName))
            {
                SQLControl sql = new SQLControl(estimateDatabaseString);
                sql.AddParam("@jobNumber", _jobNumber);
                sql.AddParam("@systemName", systemName);
                sql.AddParam("@phaseCode", phaseCode);

                sql.ExecQuery("SELECT TOP(1) EarnedHours FROM EstimateMain WHERE SystemName = @systemName AND PhaseCode = @phaseCode AND JobNumber = @jobNumber");
                //sql.ExecQuery("SELECT * FROM EstimateMain");
                if (sql.HasException())
                {
                    throw new Exception(sql.Exception.ToString());
                }
                else if (sql.DBDT.Rows.Count == 0)
                {
                    //MessageBox.Show("There doesn't appear to be a record for the system: " + systemName + " in Job Number: " + _jobNumber + ". This could be:  \n" +
                    //    "1. Because of a mismatch in system names between the name contained in the estimate sheet and the name contained in the report. \n" +
                    //    "2. Because a phase code was included on the CSV report that wasn't included in the original Estimate." );
                    return(0);
                }
                else
                {
                    double earnedHours = Convert.ToDouble(sql.DBDT.Rows[0].ItemArray[0].ToString());
                    return(earnedHours);
                }
            }
            else
            {
                return(0);
            }
        }
Exemple #3
0
        private void Add_Click(object sender, EventArgs e)
        {
            SQLControl controle = new SQLControl();

            controle.InsertLocalTable(Nome.Text, Endereco.Text);
            MessageBox.Show("Inserido com sucesso.", "Sucesso!");
        }
Exemple #4
0
        public IActionResult DownLoad()
        {
            string token = Request.Cookies["Token"];

            string[] p = Request.Headers["Path"].ToString().Split('/');
            //string[] p = "./ALL01UMD.sav".Split('/');
            if (Token.CheckToken(token))
            {
                string ID = token.Split("-")[0];
                ID = ID.Substring(0, ID.Length - 10);
                DataTable table;
                if ((table = SQLControl.Select($"SELECT * FROM testbase.UserTable where  ID={ID};")) == null)
                {
                    return(StatusCode(500, JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "数据库错误", Message = "Error"
                    })));
                }
                string name = table.Rows[0][1].ToString();
                if ((table = SQLControl.Select($"SELECT * FROM testbase.UserFileTable where UserName='******';")) == null)
                {
                    return(StatusCode(500, JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "数据库错误", Message = "Error"
                    })));
                }
                JToken         file     = JToken.Parse(table.Rows[0][1].ToString());
                Queue <string> pathlist = new Queue <string>(p);
                JToken         nowdir   = Dir.Intodir(file, pathlist);
                if (nowdir == null)
                {
                    return(BadRequest(JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "文件路径错误", Message = "Error"
                    })));
                }
                if ((table = SQLControl.Select($"SELECT * FROM testbase.HashTable where ID={nowdir["data"]};")) == null)
                {
                    return(StatusCode(500, JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "数据库错误", Message = "Error"
                    })));
                }
                string filepath = table.Rows[0][2].ToString();
                return(File(new FileStream(filepath, FileMode.Open), "application/octet-stream", p[p.Length - 1]));
            }
            else
            {
                return(BadRequest(JsonConvert.SerializeObject(new ReturnMode()
                {
                    Data = "Token错误", Message = "Error"
                })));
            }
        }
Exemple #5
0
        public string Register()
        {
            string     Json = "";
            string     a    = new StreamReader(HttpContext.Request.Body).ReadToEnd();
            SingInMode user = JsonConvert.DeserializeObject <SingInMode>(a);

            if (!string.IsNullOrEmpty(user.Name) | !string.IsNullOrWhiteSpace(user.Name) | !string.IsNullOrEmpty(user.Pwds) | !string.IsNullOrWhiteSpace(user.Pwds))
            {
                if (0 != SQLControl.Execute($"insert CDNABASE.UserTable value (0 ,'{user.Name}','{user.Pwds}');"))
                {
                    if (0 != SQLControl.Execute($"insert CDNABASE.UserDataTable value ('{user.Name}','{user.PhoneNumber}','InitialImage.jpg');"))
                    {
                        if (0 != SQLControl.Execute($"insert CDNABASE.UserFileTable value ('{user.Name}','{Token.s}',1);"))
                        {
                            Json = JsonConvert.SerializeObject(new ReturnMode()
                            {
                                Data = "注册成功", Message = "OK"
                            });
                        }
                        else
                        {
                            Json = JsonConvert.SerializeObject(new ReturnMode()
                            {
                                Data = "注册失败,服务器错误", Message = "Error"
                            });
                        }
                    }
                    else
                    {
                        Json = JsonConvert.SerializeObject(new ReturnMode()
                        {
                            Data = "注册失败,服务器错误", Message = "Error"
                        });
                    }
                }
                else
                {
                    Json = JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "注册失败,或有重复用户名", Message = "Error"
                    });
                }
            }
            else
            {
                Json = JsonConvert.SerializeObject(new ReturnMode()
                {
                    Data = "空!", Message = "Error"
                });
            }
            return(Json);
        }
Exemple #6
0
        /// <summary>
        /// Returns the 'Original_Est_Hours' from [JC_PHASE_MASTER_MC] for the provided Job Number and Phase Code, where Cost Type is always "L" for "Labor"
        /// </summary>
        /// <param name="phaseCode"></param>
        /// <returns></returns>

        //public double GetBudgetedHoursByPhaseCode(string phaseCode)
        //{
        //    phaseCode = phaseCode.Remove(4, 1);
        //    SQLControl sql = new SQLControl(spectrumDatabaseString);
        //    //sql.AddParam("@jobNumber", _jobNumber);
        //    sql.AddParam("@jobNumber", "   " + _jobNumber);
        //    sql.AddParam("@phaseCode", phaseCode);
        //    sql.AddParam("@costType", "L");
        //    //sql.AddParam("@costType", "L");
        //    //sql.ExecQuery("SELECT TOP(1) Original_Est_Hours FROM JC_PHASE_MASTER_MC WHERE Phase_Code = @phaseCode AND Job_Number = @jobNumber AND Cost_Type = @costType");
        //    sql.ExecQuery("SELECT TOP(1) Projected_Hours FROM JC_PROJ_COST_HISTORY_MC WHERE Phase = @phaseCode AND Job = @jobNumber AND Cost_Type = @costType");

        //    //sql.ExecQuery("SELECT * FROM EstimateMain");
        //    if (sql.HasException())
        //    {
        //        throw new Exception(sql.Exception.ToString());
        //    }
        //    else if (sql.DBDT.Rows.Count == 0)
        //    {
        //        //MessageBox.Show("There doesn't appear to be a record for the system: " + systemName + " in Job Number: " + _jobNumber + ". This could be:  \n" +
        //        //    "1. Because of a mismatch in system names between the name contained in the estimate sheet and the name contained in the report. \n" +
        //        //    "2. Because a phase code was included on the CSV report that wasn't included in the original Estimate." );
        //        return 0;
        //    }
        //    else
        //    {
        //        //int budgetedHours = Convert.ToInt32(sql.DBDT.Rows[0].ItemArray[0].ToString());
        //        double budgetedHours = Convert.ToDouble(sql.DBDT.Rows[0].ItemArray[0].ToString());
        //        return budgetedHours;
        //    }
        //}


        /// <summary>
        /// Returns the "Projected_Hours" field from the "JC_PROJ_COST_HISTORY_MC" table in SPECTRUM.
        /// </summary>
        /// <param name="phaseCode"></param>
        /// <returns></returns>
        public double GetProjectedHoursByPhaseCode(string phaseCode)
        {
            if (_dataProvider.UsingExternalCache == true)
            {
                return(externalDataCache.GetProjectedHoursByPhaseCode(phaseCode));
            }
            else
            {
                try
                {
                    phaseCode = phaseCode.Remove(4, 1);
                    //SQLControl sql = new SQLControl(spectrumDatabaseString);
                    SQLControl sql = new SQLControl(spectrumDatabaseString);

                    //sql.AddParam("@jobNumber", _jobNumber);
                    sql.AddParam("@jobNumber", "   " + _jobNumber);
                    sql.AddParam("@phaseCode", phaseCode);
                    sql.AddParam("@costType", "L");

                    sql.ExecQuery("SELECT SUM(Projected_Hours) FROM JC_PROJ_COST_HISTORY_MC WHERE Phase = @phaseCode AND Job = @jobNumber AND Cost_Type = @costType");

                    //sql.ExecQuery("SELECT * FROM EstimateMain");
                    if (sql.HasException())
                    {
                        return(externalDataCache.GetProjectedHoursByPhaseCode(phaseCode));
                    }
                    else if (sql.DBDT.Rows.Count == 0)
                    {
                        //MessageBox.Show("There doesn't appear to be a record for the system: " + systemName + " in Job Number: " + _jobNumber + ". This could be:  \n" +
                        //    "1. Because of a mismatch in system names between the name contained in the estimate sheet and the name contained in the report. \n" +
                        //    "2. Because a phase code was included on the CSV report that wasn't included in the original Estimate." );
                        return(0);
                    }
                    else
                    {
                        //int budgetedHours = Convert.ToInt32(sql.DBDT.Rows[0].ItemArray[0].ToString());
                        double projectedHours = Convert.ToDouble(sql.DBDT.Rows[0].ItemArray[0].ToString());
                        return(projectedHours);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                    throw;
                }
            }
        }
        public IActionResult PostList()
        {
            string Json = "";

            string[]       p    = new StreamReader(Request.Body).ReadToEnd().Split('/');
            Queue <string> path = new Queue <string>(p);
            string         a    = Request.Cookies["Token"];

            if (Token.CheckToken(a))
            {
                string ID = a.Split("-")[0];
                ID = ID.Substring(0, ID.Length - 10);
                DataTable table;
                if ((table = SQLControl.Select($"SELECT * FROM testbase.UserTable where  ID = {ID};")) == null)
                {
                    return(StatusCode(500, JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "数据库错误", Message = "Error"
                    })));
                }
                string name = table.Rows[0][1].ToString();
                table = null;
                if ((table = SQLControl.Select($"SELECT * FROM testbase.UserFileTable where UserName = '******';")) == null)
                {
                    return(StatusCode(500, JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "数据库错误", Message = "Error"
                    })));
                }
                JToken file   = JToken.Parse(table.Rows[0][1].ToString());
                JToken nowdir = Dir.Intodir(file, path);
                Json = JsonConvert.SerializeObject(new ReturnMode()
                {
                    Data = nowdir.ToString(), Message = "OK"
                });
                return(Ok(Json));
            }
            else
            {
                return(BadRequest(JsonConvert.SerializeObject(new ReturnMode()
                {
                    Data = "Token错误", Message = "Error"
                })));
            }
        }
        private bool ProbeSpectrumDatabase()
        {
            string     spectrumDatabaseString = ConnectionStringService.GetConnectionString("Spectrum");
            SQLControl sql = new SQLControl(spectrumDatabaseString);

            //sql.AddParam("@jobNumber", _jobNumber);

            //sql.AddParam("@costType", "L");
            sql.ExecQuery("SELECT * FROM JC_TRANSACTION_HISTORY_MC WHERE Job_Number = '   2190302'");
            if (sql.HasException())
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
 public string Post()
 {
     string Json = "";
     string a = new StreamReader(HttpContext.Request.Body).ReadToEnd();
     UserMode user = JsonConvert.DeserializeObject<UserMode>(a);
     if (!string.IsNullOrEmpty(user.Name) | !string.IsNullOrWhiteSpace(user.Name) | !string.IsNullOrEmpty(user.Pwds) | !string.IsNullOrWhiteSpace(user.Pwds))
     {
         DataTable s;
         if ((s = SQLControl.Select($"SELECT * FROM CDNABASE.UserTable where  UserName='******'and PassWord='******';")) == null)
             Json = JsonConvert.SerializeObject(new ReturnMode() { Data = "数据库错误", Message = "Error" });
         if (s.Rows.Count != 0)
             Json = JsonConvert.SerializeObject(new ReturnMode() { Data = Token.GetToken(s.Rows[0][0].ToString()), Message = "OK" });
         else
             Json = JsonConvert.SerializeObject(new ReturnMode() { Data = "用户名密码错误", Message = "Error" });
     }
     else
         Json = JsonConvert.SerializeObject(new ReturnMode() { Data = "空!", Message = "Error" });
     return Json;
 }
Exemple #10
0
        //TODO: Refence this function in the SPECTRUM-related procedures above.
        private bool ValidateSPECTRUMPhaseCode(string phaseCode)
        {
            SQLControl sql = new SQLControl(estimateDatabaseString);

            sql.AddParam("@jobNumber", _jobNumber);
            sql.AddParam("@phaseCode", phaseCode);
            sql.ExecQuery("SELECT * FROM EstimateMain WHERE JobNumber = @jobNumber AND PhaseCode = @phaseCode");
            if (sql.HasException())
            {
                throw new Exception(sql.Exception.ToString());
            }
            else if (sql.DBDT.Rows.Count == 0)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Exemple #11
0
        /// <summary>
        /// Commits the SystemEstimate objects contained in the provided list to the database.
        /// </summary>
        /// <param name="systemEstimateList"></param>
        public void Commit(List <SystemEstimate> systemEstimateList)
        {
            //Convert the systemEstimateLIst into EstimateTransaction form, ready for database commit.
            List <EstimateTransaction> transactionData = ConvertToEstimateTransaction(systemEstimateList);

            if (transactionData != null && transactionData.Count != 0)
            {
                try
                {
                    //Insert a new header entry into the database.
                    SQLControl sql = new SQLControl(ConnectionStringService.GetConnectionString("Estimate"));
                    sql.AddParam("@jobNumber", _jobNumber);
                    sql.AddOutputParam("@estimateID", SqlDbType.Int, 4);
                    int nextEstimateID = (int)sql.GetReturnValueFromStoredProcedure("spInsertEstimateHeader", "@estimateID");

                    //If the new estimate header was successfully added, continue with the process.
                    if (nextEstimateID > 0)
                    {
                        //Assign the estimate ID to the transaction objects.
                        //int newEstimateID = 12;
                        foreach (EstimateTransaction t in transactionData)
                        {
                            t.EstimateID = nextEstimateID;
                        }

                        //Send the transaction list to be inserted in the database.
                        InsertMultipleRecords(transactionData);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message.ToString());
                    throw;
                }
            }
            else
            {
                throw new Exception("Estimate commit aborted because transaction data list failed to populate correctly.");
            }
        }
Exemple #12
0
        /// <summary>
        /// Returns true if the job number is found in the estimating database.  Only one estimate record is allowed per job number.
        /// </summary>
        /// <param name="jobNumber"></param>
        /// <returns></returns>
        public bool IsDuplicateJobNumber(string jobNumber)
        {
            using (SQLControl sql = new SQLControl(ConnectionStringService.GetConnectionString("Estimate")))
            {
                sql.AddParam("@jobNumber", jobNumber);
                sql.ExecQuery("SELECT * FROM EstimateHeader WHERE JobNumber = @jobNumber");

                if (sql.HasException())
                {
                    throw new Exception("Error in SQLControl class while attempting to detect duplicate job numbers.");
                }

                if (sql.DBDT.Rows.Count == 0)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            };
        }
Exemple #13
0
        /// <summary>
        /// Validates the provided system name by matching it with a corresponding entry in the 'EstimateMain' table.
        /// </summary>
        /// <param name="systemName"></param>
        /// <returns></returns>
        public bool ValidateSystemName(string systemName)
        {
            //To avoid displaying multiple error messages for the same system, a list of systems for which errors have been displayed is kept.  When the next error
            //is triggered, the message will only display if the system is not found in this list.
            List <string> uniqueSystemsList = new List <string>();

            SQLControl sql = new SQLControl(estimateDatabaseString);

            sql.AddParam("@jobNumber", _jobNumber);
            sql.AddParam("@systemName", systemName);
            sql.ExecQuery("SELECT * FROM EstimateMain WHERE SystemName = @systemName AND JobNumber = @jobNumber");
            if (sql.HasException())
            {
                throw new Exception(sql.Exception.ToString());
            }
            else if (sql.DBDT.Rows.Count == 0)
            {
                if (uniqueSystemsList.Contains(systemName))
                {
                    //Do nothing.
                }
                else
                {
                    MessageBox.Show("The system: " + systemName + " was not found in the Estimate record.  This could be due to a mismatch between the case/spelling used in " +
                                    "CSV report file.  Check the Estimate sheet for the job and make sure the system names match exactly.  If they do not, alter the CSV file entry and try again");

                    //Add the system name to the uniqueSystemsList so that no more error messages appear for this system.
                    uniqueSystemsList.Add(systemName);
                }
                return(false);
            }
            else
            {
                return(true);
            }
        }
Exemple #14
0
        /// <summary>
        /// Returns the summed earnedhours from EstimateMain for provided jobnumber and phase code
        /// </summary>
        /// <param name="phaseCode"></param>
        /// <returns></returns>
        public double GetTeamBudgetHours(string phaseCode)
        {
            if (ValidateEstimatePhaseCode(phaseCode))
            {
                SQLControl sql = new SQLControl(estimateDatabaseString);
                //sql.AddParam("@jobNumber", _jobNumber);
                sql.AddParam("@jobNumber", _jobNumber);
                sql.AddParam("@phaseCode", phaseCode);
                //sql.AddParam("@costType", "L");
                sql.ExecQuery("SELECT SUM(EarnedHours) FROM EstimateMain WHERE JobNumber = @jobNumber AND PhaseCode = @phaseCode");

                //sql.ExecQuery("SELECT * FROM EstimateMain");
                if (sql.HasException())
                {
                    throw new Exception(sql.Exception.ToString());
                }
                else if (sql.DBDT.Rows.Count == 0 || sql.DBDT == null)
                {
                    //MessageBox.Show("There doesn't appear to be a record for the system: " + systemName + " in Job Number: " + _jobNumber + ". This could be:  \n" +
                    //    "1. Because of a mismatch in system names between the name contained in the estimate sheet and the name contained in the report. \n" +
                    //    "2. Because a phase code was included on the CSV report that wasn't included in the original Estimate." );
                    return(0);
                }
                else
                {
                    //int budgetedHours = Convert.ToInt32(sql.DBDT.Rows[0].ItemArray[0].ToString());
                    //int teamBudgetHours = Convert.ToInt32(sql.DBDT.Rows[0].ItemArray[0].ToString());
                    double teamBudgetHours = Convert.ToDouble(sql.DBDT.Rows[0].ItemArray[0].ToString());
                    return(teamBudgetHours);
                }
            }
            else
            {
                return(0);
            }
        }
        // events ---------------------------------------------------------------------

        private void LoginWindow1_Load(object sender, EventArgs e)
        {
            // Create Folder / File structure
            InitilizeFolderStructure();

            // Initilize Profile Window
            PW = new ProfileWindow(this);

            // Initilize SQL Control
            SQLControl SC = new SQLControl(textBox4.Text, textBox3.Text, "192.168.86.38");// update after we add a textbox for serverip input

            Globals._SC = SC;

            // Load Last SQL Settings
            Functions.LoadSettings();
            textBox3.Text = Globals._Settings["SQL Database"];
            textBox4.Text = Globals._Settings["SQL Server"];
            try
            {
                if (Globals._Settings["Remember Username"] == "true")
                {
                    checkBox1.Checked = true;
                    textBox2.Text     = Globals._Settings["SQL Username"];
                }
            }
            catch (Exception ex)
            {
            }


            // Initilize Verification Thread and run it
            if (textBox3.Text != "" && textBox4.Text != "")
            {
                new Thread(VerifyConnection).Start();
            }
        }
        public IActionResult DownLoad()
        {
            string token = Request.Cookies["Token"];

            string[] p = Request.Headers["Path"].ToString().Split('/');
            //string[] p = "./ALL01UMD.sav".Split('/');
            if (Token.CheckToken(token))
            {
                string ID = token.Split("-")[0];
                ID = ID.Substring(0, ID.Length - 10);
                DataTable table;
                if ((table = SQLControl.Select($"SELECT * FROM CDNABASE.UserTable where  ID={ID};")) == null)
                {
                    return(StatusCode(500, JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "数据库错误", Message = "Error"
                    })));
                }
                string name = table.Rows[0][1].ToString();
                if ((table = SQLControl.Select($"SELECT * FROM CDNABASE.UserFileTable where UserName='******';")) == null)
                {
                    return(StatusCode(500, JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "数据库错误", Message = "Error"
                    })));
                }
                JToken         file     = JToken.Parse(table.Rows[0][1].ToString());
                Queue <string> pathlist = new Queue <string>(p);
                JToken         nowdir   = Dir.Intodir(file, pathlist);
                if (nowdir == null)
                {
                    return(BadRequest(JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "文件路径错误", Message = "Error"
                    })));
                }
                if ((table = SQLControl.Select($"SELECT * FROM CDNABASE.HashTable where ID={nowdir["data"]};")) == null)
                {
                    return(StatusCode(500, JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "数据库错误", Message = "Error"
                    })));
                }
                string         filepath   = table.Rows[0][2].ToString();
                bool           k          = false;
                CDNAFileStream filestream = null;
                foreach (string key in streamtable.Keys)
                {
                    if (key == filepath)
                    {
                        k          = true;
                        filestream = streamtable[key];
                        break;
                    }
                }
                if (!k)
                {
                    filestream = new CDNAFileStream(filepath, FileMode.Open);
                    streamtable.Add(filepath, filestream);
                }
                long   length = filestream.Length;
                byte[] data   = new byte[length];
                for (long i = 0; i < filestream.Length; i++)
                {
                    while (!filestream.ISREAD)
                    {
                        ;
                    }
                    filestream.ISREAD = false;
                    long nowpo = filestream.Position;
                    filestream.Seek(i, SeekOrigin.Begin);
                    data[i] = (byte)filestream.ReadByte();
                    filestream.Seek(nowpo, SeekOrigin.Begin);
                    filestream.ISREAD = true;
                }
                return(File(data, "application/octet-stream", p[p.Length - 1]));
            }
            else
            {
                return(BadRequest(JsonConvert.SerializeObject(new ReturnMode()
                {
                    Data = "Token错误", Message = "Error"
                })));
            }
        }
Exemple #17
0
        //[DisableFormValueModelBinding]
        //[RequestFormLimits(MultipartBodyLengthLimit = 200 * 1024 * 1024)]
        public IActionResult UpLoad()
        {
            string token = Request.Cookies["Token"];

            string[] p = Request.Headers["Path"].ToString().Split('/');
            //string[] p = "./A/".Split('/');
            var files = Request.Form.Files;

            if (Token.CheckToken(token) && files != null)
            {
                Stream stream       = null;
                string saveFilePath = null;
                JArray filestr      = null;
                string name         = null;
                try
                {
                    foreach (var file in files)
                    {
                        string ID = token.Split("-")[0];
                        ID = ID.Substring(0, ID.Length - 10);
                        DataTable table;
                        if ((table = SQLControl.Select($"SELECT * FROM testbase.UserTable where  ID={ID};")) == null)
                        {
                            throw new NewSqlException();
                        }
                        name = table.Rows[0][1].ToString();

                        filestr = null;
                        stream  = file.OpenReadStream();
                        byte[] hash = Save_ReadFile.GetHash(stream);

                        MySqlParameter hashParameter = new MySqlParameter("@hash", MySqlDbType.TinyBlob);
                        hashParameter.Value = hash;
                        int fileID = 0;
                        //检查Hash表里是否有这个文件
                        if (-1 == (fileID = SQLControl.Select($"SELECT * FROM testbase.HashTable where Hash = @hash;", hashParameter)))
                        {//没有就加进去
                            string filename = DateTime.Now.ToString("yyyyMMddhhmmss");
                            while (System.IO.File.Exists(FilePath + filename))
                            {
                                filename = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random().Next(10);
                            }
                            if (!Save_ReadFile.SaveFile(FilePath + filename, file))
                            {
                                throw new IOException();
                            }
                            MySqlParameter blobParameter = new MySqlParameter("@hash", MySqlDbType.TinyBlob);
                            blobParameter.Value = hash;
                            if (0 == SQLControl.Execute($"insert testbase.HashTable value (0,@hash,'{FilePath + filename}');", blobParameter))
                            {
                                throw new NewSqlException();
                            }
                            fileID = SQLControl.Select($"SELECT * FROM testbase.HashTable where Hash = @hash;", blobParameter);
                        }
                        //把Hash绑定到用户文件列表上
                        do
                        {
                            table = null;
                            if ((table = SQLControl.Select($"SELECT * FROM testbase.UserFileTable where UserName='******';")) == null)
                            {
                                throw new NewSqlException();
                            }
                        } while (int.Parse(table.Rows[0][2].ToString()) != 1);
                        filestr = JArray.Parse(table.Rows[0][1].ToString());
                        Queue <string> pathlist = new Queue <string>(p);
                        JObject        jo       = new JObject();
                        Encoding       encoding = Encoding.Default;
                        jo.Add("time", DateTime.Now.ToString("yyyy-MM-dd"));
                        jo.Add("name", file.FileName);
                        jo.Add("type", "file");
                        jo.Add("size", file.Length);
                        jo.Add("data", fileID);
                        JToken newdir = Dir.AddJson(filestr, pathlist, JToken.Parse(jo.ToString()));

                        SQLControl.Execute($"UPDATE testbase.UserFileTable SET File='' , State = 0 where UserName='******';");
                        SQLControl.Execute($"UPDATE testbase.UserFileTable SET File='{newdir.ToString()}',State = 1 where UserName='******';");
                    }
                }
                catch (IOException)
                {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                    if (System.IO.File.Exists(saveFilePath))
                    {
                        System.IO.File.Delete(saveFilePath);
                    }
                    return(StatusCode(500, JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "服务器保存错误", Message = "Error"
                    })));
                }
                catch (NewSqlException)
                {
                    return(StatusCode(500, JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "数据库错误", Message = "Error"
                    })));
                }
                catch (MySqlException)
                {
                    if (filestr != null)
                    {
                        SQLControl.Execute($"UPDATE testbase.UserFileTable SET File='{filestr.ToString()}' , State = 1 where UserName='******';");
                    }
                }
            }
            else
            {
                return(BadRequest(JsonConvert.SerializeObject(new ReturnMode()
                {
                    Data = "Token错误", Message = "Error"
                })));
            }
            return(Ok(JsonConvert.SerializeObject(new ReturnMode()
            {
                Data = "保存完成!", Message = "OK"
            })));
        }
Exemple #18
0
 public CreateAccount(SQLControl SControl)
 {
     InitializeComponent();
     SC = SControl;
 }
Exemple #19
0
        public IActionResult AddDir()
        {
            string token = Request.Cookies["Token"];

            string[]       p       = Request.Headers["Path"].ToString().Split('/');
            string         dirname = Request.Headers["DirName"].ToString();
            string         name    = "";
            JArray         filestr = null;
            Queue <string> q       = new Queue <string>(p);
            DataTable      table   = null;

            try
            {
                if (Token.CheckToken(token))
                {
                    string ID = token.Split("-")[0];
                    ID = ID.Substring(0, ID.Length - 10);
                    if ((table = SQLControl.Select($"SELECT * FROM testbase.UserTable where  ID={ID};")) == null)
                    {
                        throw new NewSqlException();
                    }
                    name = table.Rows[0][1].ToString();
                    if ((table = SQLControl.Select($"SELECT * FROM testbase.UserFileTable where UserName='******';")) == null)
                    {
                        throw new NewSqlException();
                    }
                    do
                    {
                        table = null;
                        if ((table = SQLControl.Select($"SELECT * FROM testbase.UserFileTable where UserName='******';")) == null)
                        {
                            throw new NewSqlException();
                        }
                    } while (int.Parse(table.Rows[0][2].ToString()) != 1);
                    filestr = JArray.Parse(table.Rows[0][1].ToString());
                    JObject job = new JObject();
                    job["time"] = DateTime.Now.ToString("yyyy-MM-dd");
                    job["name"] = dirname;
                    job["type"] = "dir";
                    job["data"] = "[]";
                    JToken newdir = Dir.AddJson(filestr, q, JToken.Parse(job.ToString()));

                    SQLControl.Execute($"UPDATE testbase.UserFileTable SET File='' , State = 0 where UserName='******';");
                    SQLControl.Execute($"UPDATE testbase.UserFileTable SET File='{newdir.ToString()}',State = 1 where UserName='******';");
                }
                else
                {
                    return(BadRequest(JsonConvert.SerializeObject(new ReturnMode()
                    {
                        Data = "Token错误", Message = "Error"
                    })));
                }
            }
            catch (NewSqlException)
            {
                return(StatusCode(500, JsonConvert.SerializeObject(new ReturnMode()
                {
                    Data = "数据库错误", Message = "Error"
                })));
            }
            catch (MySqlException)
            {
                if (filestr != null)
                {
                    SQLControl.Execute($"UPDATE testbase.UserFileTable SET File='{filestr.ToString()}' , State = 1 where UserName='******';");
                }
            }
            return(Ok());
        }