Пример #1
0
        public ActionResult Register(RegisterModel model)
        {
            try
            {
                User user = null;
                using (ISession session = NHibertnateSession.OpenSession())
                {
                    user = session.Query <User>().FirstOrDefault(u => u.Login == model.Login);
                }
                if (user == null)
                {
                    using (ISession session = NHibertnateSession.OpenSession())
                    {
                        using (ITransaction transaction = session.BeginTransaction())
                        {
                            session.Save(new User()
                            {
                                Login = model.Login, Password = MD5Class.Calculate(model.Password).ToLower()
                            });
                            transaction.Commit();
                            FormsAuthentication.SetAuthCookie(model.Login, true);
                            return(RedirectToAction("Index", "Home"));
                        }
                    }
                }

                ModelState.AddModelError("", "Пользователь с таким логином уже существует");
            }
            catch
            {
                return(View(model));
            }

            return(View(model));
        }
Пример #2
0
        /// <summary>
        /// Checking the integrity: Checking if the all components present and Checking 7-zip intergrity
        /// </summary>
        static void CheckIntergrity()
        {
            try
            {
                Directories.CriticalFoldersCheck();
                Files.CriticalFilesCheck();
            }
            catch (DirectoryNotFoundException e)
            {
                _packageIsBroken = true;
                Messages.ShowErrorBox(string.Format(Translation.Current[580], e.Message));
            }
            catch (FileNotFoundException e)
            {
                _packageIsBroken = true;
                Messages.ShowErrorBox(string.Format(Translation.Current[580], e.Message));
            }

            // Checking 7-zip intergrity
            try
            {
                MD5Class.Verify7ZipBinaries();
            }
            catch (InvalidSignException ee)
            {
                _7ZipIsBroken = true;
                Messages.ShowErrorBox(string.Format(Translation.Current[541], ee.Message));
            }

            _schedulerInstalled = File.Exists(Files.Scheduler);
        }
Пример #3
0
        private static void sign(string file, string md5File)
        {
            try
            {
                if (!string.IsNullOrEmpty(file))
                {
                    if (File.Exists(md5File))
                    {
                        File.Delete(md5File);
                    }

                    string srcMd5 = MD5Class.GetFileMD5(file);
                    File.WriteAllText(md5File, srcMd5);
                }
                else
                {
                    Console.WriteLine(_InputFileNotSpecified);
                }
            }
            catch
            {
                Console.Beep();
                throw;
            }
        }
 public ActionResult Add(Document model)
 {
     try
     {
         if (!ModelState.IsValid)
         {
             return(View(model));
         }
         var file = Request.Files[0];
         if (file == null)
         {
             return(View(model));
         }
         using (ISession session = NHibertnateSession.OpenSession())
         {
             DateTime dateTime  = DateTime.Now;
             string   timeStamp = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds.ToString();
             var      link      = MD5Class.Calculate($"{timeStamp}{model.Name}").ToLower();
             var      fileExt   = Path.GetExtension(file.FileName);
             var      path      = Path.Combine(Server.MapPath("~/App_Data/uploads"), $"{link}{fileExt}");
             file.SaveAs(path);
             session.CreateSQLQuery("EXEC AddDocument @name = '" + model.Name + "',@date = '" + dateTime +
                                    "',@author = '" + User.Identity.Name + "',@link = '" + link +
                                    "', @contentPath = '" + path + "'")
             .ExecuteUpdate();
         }
     }
     catch
     {
         // ignored
     }
     return(RedirectToAction("All", "Documents"));
 }
Пример #5
0
 /// <summary>
 /// 将指定的字符串进行MD5编码
 /// </summary>
 /// <param name="Src">要进行编码的串</param>
 /// <returns>返回字符串表现形式的编码串</returns>
 public static string MD5(string Src)
 {
     if (string.IsNullOrEmpty(Src))
     {
         return("");
     }
     return(MD5Class.MDString(Src));
 }
Пример #6
0
        public RBACUserInfo GetUser(string username)
        {
            try
            {
                // Get dataset of filtered users from DB (Note: this will contain more info than from the RBAC method)
                Dictionary <string, object> sqlParams = new Dictionary <string, object>();
                sqlParams.Add("@UserName", username);
                DataSet _dsUsers = _DAL_RBAC.GetDatasetFromSQL(
                    "select CONVERT(VARBINARY(85), UserID) AS DBUserSid, UserID, UserName, DomainUserName, Password, FullName, CustomerID from Users where UserName = @UserName order by UserName", sqlParams, true);
                _dsUsers.Tables[0].TableName = "Users";

                if (_dsUsers.Tables[0].Rows.Count == 0)
                {
                    _dsUsers.Dispose();
                    return(null);
                }

                // Get specific user from RBAC
                RBACUserInfo rbacUser = null;
                rbacUser = new RBACUserInfo();
                DataRow nextRow = _dsUsers.Tables["Users"].Rows[0];

                rbacUser.UserName       = Convert.ToString(nextRow["UserName"]);
                rbacUser.FullName       = Convert.ToString(nextRow["FullName"]);
                rbacUser.DomainUserName = Convert.ToString(nextRow["DomainUserName"]);

                if (nextRow["DBUserSid"] != DBNull.Value)
                {
                    rbacUser.DBUserCustomSID = (nextRow["DBUserSid"] as byte[]);
                }

                if (nextRow["CustomerID"] != DBNull.Value)
                {
                    rbacUser.PEMDefaultCustomerID = Convert.ToInt32(nextRow["CustomerID"]);
                }

                // Retrieve persisted password bytes, then convert to a string, and then decode from Base64 encoding
                rbacUser.Password_StoredBytes = nextRow["Password"] as byte[];
                byte[] pwdBytes = nextRow["Password"] as byte[];
                string userPwd  = ASCIIEncoding.ASCII.GetString(pwdBytes);
                pwdBytes = Convert.FromBase64String(userPwd);
                rbacUser.Password_Encrytped = userPwd;
                // Create DES decryption key that is based on the username (reversed string)
                string Key       = MD5Class.Reverse(rbacUser.UserName /*rbacUser.DBUser.UserName*/);
                string SecretKey = MD5Class.ConvertToMD5(Key);
                // Decrypt stored password using DES
                SymmetricEncryption SE = new SymmetricEncryption(EncryptionType.DES);
                string MDecrypt        = SE.Decrypt(userPwd, SecretKey);
                rbacUser.Password_PlainText = MDecrypt; // Decrypted password (Plain-text)
                _dsUsers.Dispose();
                return(rbacUser);
            }
            catch
            {
                return(null);
            }
        }
Пример #7
0
 private static void showMd5(string file)
 {
     if (!string.IsNullOrEmpty(file))
     {
         Console.WriteLine(MD5Class.GetFileMD5(file));
     }
     else
     {
         Console.WriteLine(_InputFileNotSpecified);
     }
 }
Пример #8
0
        /// <summary>
        /// Called in the very beginning of backup lifetime cycle
        /// </summary>
        bool BeforeBackup(out Collection <MetaRecord> metarecords, out ArchiveTask[] archiveParameters)
        {
            _log.ProcedureCall("BeforeBackUp");
            _log.WriteLine(LoggingEvent.Debug, string.Format(CultureInfo.InvariantCulture, "Temp folder: {0}", Directories.TempFolder));
            _log.WriteLine(LoggingEvent.Debug, string.Format(CultureInfo.InvariantCulture, "Task: {0}", _task.Name));

            if ((_log is FileLog) && (_options.LoggingLevel == LogLevel.Support))
            {
                string[] options = File.ReadAllLines(Files.ProfileFile);

                foreach (string line in options)
                {
                    _log.WriteLine(LoggingEvent.Debug, line.Replace("<", "(").Replace(">", ")"));
                }
            }

            foreach (BackupEventTaskInfo taskInfo in _task.BeforeBackupTasksChain)
            {
                Notify(new RunProgramBeforeOrAfterBackupEventArgs(taskInfo, ProcessingState.NotStarted));
            }

            foreach (BackupEventTaskInfo taskInfo in _task.AfterBackupTasksChain)
            {
                Notify(new RunProgramBeforeOrAfterBackupEventArgs(taskInfo, ProcessingState.NotStarted));
            }

            archiveParameters = CreateArgsForCompressionAndMetaForImage(out metarecords);
            foreach (ArchiveTask archiveParameter in archiveParameters)
            {
                Notify(new PackingNotificationEventArgs(archiveParameter.ItemToCompress, ProcessingState.NotStarted));
            }

            foreach (StorageBase storage in _task.Storages)
            {
                Notify(new CopyingToStorageNotificationEventArgs(storage, ProcessingState.NotStarted));
            }

            Notify(new ImagePackingNotificationEventArgs(ProcessingState.NotStarted));

            try
            {
                MD5Class.Verify7ZipBinaries();
            }
            catch (InvalidSignException signException)
            {
                _log.WriteLine(LoggingEvent.Error, string.Format(Translation.Current[541], signException.Message));
                return(false);
            }

            return(IsAnySenceInPacking());
        }
Пример #9
0
 /// <summary>
 /// Checks integrity of 7-zip software. In case it's incorrect,
 /// writes event to program log and halts application
 /// Does not throw any exceptons
 /// </summary>
 private static void check7zipIntegrity()
 {
     try
     {
         MD5Class.Verify7ZipBinaries();
     }
     catch (InvalidSignException)
     {
         // there's no need in service - because installation was damaged by virus!
         seriousBugHelper(_7ZIPBINARIESWEREDAMAGED, true);
     }
     catch (Exception e)
     {
         ImproveIt.ProcessUnhandledException(e);
     }
 }
        public void AddSave(T_Base_Teacher teacher)
        {
            DALT_Base_Teacher dal = new DALT_Base_Teacher();
            string            pwd = MD5Class.UserMd5(teacher.TeaId);

            teacher.PassWord = pwd;
            bool res = dal.Add(teacher);

            if (res)
            {
                string tmp = "{\"statusCode\":\"200\",\"message\":\"插入成功\",\"navTabId\":\"TeacherList\",\"rel\":\"TeacherList\",\"callbackType\":\"closeCurrent\",\"forwardUrl\":\"\"}";
                Response.Write(tmp);
            }
            else
            {
                string tmp = "{\"statusCode\":\"300\",\"message\":\"插入失败\",\"navTabId\":\"TeacherList\",\"rel\":\"TeacherList\",\"callbackType\":\"closeCurrent\",\"forwardUrl\":\"\"}";
                Response.Write(tmp);
            }
        }
Пример #11
0
 protected void Logon_Click(object sender, EventArgs e)
 {
     if ((txtUserName.Text == "" || txtPassword.Text == "" || txtQpassword.Text == "" || txtQQ.Text == "") || (male.Checked == false && famale.Checked == false) || txtPassword.Text != txtQpassword.Text)
     {
         Response.Write("<script>alert('注册失败,请正确填写信息!')</script>");
     }
     else
     {
         if (isName())
         {
             Response.Write("<script>alert('注册失败,该用户名已被注册!')</script>");
         }
         else
         {
             string   userName = txtUserName.Text;
             MD5Class md5      = new MD5Class();
             string   userPass = md5.Md5Encrypt(txtPassword.Text);
             string   qq       = txtQQ.Text;
             string   sex      = "";
             if (male.Checked == true)
             {
                 sex = "male";
             }
             else if (famale.Checked == true)
             {
                 sex = "famale";
             }
             string    mysqlinsert = "insert into tb_user(Uid,PassWord,QQ,Sex) values('" + userName + "','" + userPass + "','" + qq + "','" + sex + "')";
             MySqlData da          = new MySqlData();
             bool      add         = da.ExceSQL(mysqlinsert);
             if (add == true)
             {
                 Response.Write("<script>alert('注册成功!')</script>");
                 txtPassword.Text = txtQpassword.Text = txtUserName.Text = txtQQ.Text = "";
             }
             else
             {
                 Response.Write("<script>alert('注册失败!')</script>");
             }
         }
     }
 }
        public void Reset(int id)
        {
            DALT_Base_Student db      = new DALT_Base_Student();
            T_Base_Student    student = db.GetStudent(id);
            string            pwd     = MD5Class.UserMd5(student.StuId);

            student.PassWord = pwd;
            bool res = db.Update(student);

            if (res)
            {
                string tmp = "{\"statusCode\":\"200\",\"message\":\"重置密码成功\",\"navTabId\":\"StudentList\",\"rel\":\"StudentList\",\"callbackType\":\"\",\"forwardUrl\":\"\"}";
                Response.Write(tmp);
            }
            else
            {
                string tmp = "{\"statusCode\":\"300\",\"message\":\"重置密码失败\",\"navTabId\":\"StudentList\",\"rel\":\"StudentList\",\"callbackType\":\"\",\"forwardUrl\":\"\"}";
                Response.Write(tmp);
            }
        }
Пример #13
0
 private static void verifyMd5(string file, string fileWithMd5)
 {
     if (!string.IsNullOrEmpty(file))
     {
         string srcMd5 = MD5Class.GetFileMD5(file);
         bool   result = (File.ReadAllText(fileWithMd5) == srcMd5);
         if (result)
         {
             Console.WriteLine(_Ok);
         }
         else
         {
             Console.WriteLine(_Bad);
         }
     }
     else
     {
         Console.WriteLine(_InputFileNotSpecified);
     }
 }
        public void Reset(int id)
        {
            DALT_Base_Teacher db      = new DALT_Base_Teacher();
            T_Base_Teacher    teacher = db.GetTeacher(id);
            string            pwd     = MD5Class.UserMd5(teacher.TeaId);

            teacher.PassWord = pwd;
            bool res = db.Update(teacher);

            if (res)
            {
                string tmp = "{\"statusCode\":\"200\",\"message\":\"重置密码成功\",\"navTabId\":\"teacherList\",\"rel\":\"teacherList\",\"callbackType\":\"\",\"forwardUrl\":\"\"}";
                Response.Write(tmp);
            }
            else
            {
                string tmp = "{\"statusCode\":\"300\",\"message\":\"重置密码失败\",\"navTabId\":\"teacherList\",\"rel\":\"teacherList\",\"callbackType\":\"\",\"forwardUrl\":\"\"}";
                Response.Write(tmp);
            }
        }
Пример #15
0
        /// <summary>
        /// Starts 7-zip and waits until it finishes its work
        /// </summary>
        /// <exception cref="FieldAccessException">Problems with 7-zip</exception>
        public void StartJob()
        {
            MD5Class.Verify7ZipBinaries();
            Process process = new Process();

            process.StartInfo.UseShellExecute = false;
            process.StartInfo.FileName        = Files.SevenZipGPacker;
            process.StartInfo.Arguments       = _parameters.ToString();

            try
            {
                process.Start();
            }
            catch (System.ComponentModel.Win32Exception exc)
            {
                throw new FieldAccessException(string.Format(CultureInfo.InvariantCulture, Translation.Current[550], exc.Message), exc);
            }

            process.WaitForExit();
        }
        public void AddSave(T_Base_Student student)
        {
            DALT_Base_Student dal = new DALT_Base_Student();
            string            pwd = MD5Class.UserMd5(student.StuId);

            student.ClassId  = Convert.ToInt32(Request.Form["Class.Id"]);
            student.PassWord = pwd;
            int res = dal.Add(student);

            if (res != 0)
            {
                string tmp = "{\"statusCode\":\"200\",\"message\":\"插入成功\",\"navTabId\":\"StudentList\",\"rel\":\"StudentList\",\"callbackType\":\"closeCurrent\",\"forwardUrl\":\"\"}";
                Response.Write(tmp);
            }
            else
            {
                string tmp = "{\"statusCode\":\"300\",\"message\":\"插入失败\",\"navTabId\":\"StudentList\",\"rel\":\"StudentList\",\"callbackType\":\"closeCurrent\",\"forwardUrl\":\"\"}";
                Response.Write(tmp);
            }
        }
Пример #17
0
        public void UpPwd(string oldpwd, string newpwd1, string newpwd2)
        {
            string          newId = Session["UserId"].ToString();
            int             id    = Convert.ToInt32(newId);
            DALT_Base_Admin dal   = new DALT_Base_Admin();
            T_Base_Admin    admin = dal.GetModel(id);

            string a = MD5Class.UserMd5(oldpwd);
            string b = MD5Class.UserMd5(newpwd1);

            if (a != admin.PassWord)
            {
                string tmp = "{\"statusCode\":\"300\",\"message\":\"旧密码错误\",\"navTabId\":\"UserList\",\"rel\":\"UserList\",\"callbackType\":\"\",\"forwardUrl\":\"\"}";
                Response.Write(tmp);
            }
            else
            {
                if (newpwd1 != newpwd2)
                {
                    string tmp = "{\"statusCode\":\"300\",\"message\":\"新密码不一致\",\"navTabId\":\"UserList\",\"rel\":\"UserList\",\"callbackType\":\"\",\"forwardUrl\":\"\"}";
                    Response.Write(tmp);
                }
                else
                {
                    admin.PassWord = b;
                    bool res = dal.Update(admin);

                    if (res)
                    {
                        string tmp = "{\"statusCode\":\"200\",\"message\":\"修改成功\",\"navTabId\":\"UserList\",\"rel\":\"UserList\",\"callbackType\":\"closeCurrent\",\"forwardUrl\":\"\"}";
                        Response.Write(tmp);
                    }
                    else
                    {
                        string tmp = "{\"statusCode\":\"300\",\"message\":\"修改失败,请重试\",\"navTabId\":\"UserList\",\"rel\":\"UserList\",\"callbackType\":\"\",\"forwardUrl\":\"\"}";
                        Response.Write(tmp);
                    }
                }
            }
        }
Пример #18
0
        protected void Login_Click(object sender, EventArgs e)
        {
            string code = txtCode.Text;

            if (Request.Cookies["CheckCode"].Value == code)
            {
                MySqlConnection con = new MySqlConnection("server=localhost;database=messageboard;User id=root;password=095637");
                con.Open();
                MD5Class     md5      = new MD5Class();
                string       pass     = md5.Md5Encrypt(txtPassword.Text);
                string       mysqlSel = "select *from tb_user where Uid=@username and PassWord=@userpass";
                MySqlCommand com      = new MySqlCommand(mysqlSel, con);
                com.CommandType = System.Data.CommandType.Text;
                com.Parameters.Add(new MySqlParameter("username", MySqlDbType.VarChar, 20));
                com.Parameters["username"].Value = txtUserName.Text;
                com.Parameters.Add(new MySqlParameter("userpass", MySqlDbType.VarChar, 100));
                com.Parameters["userpass"].Value = pass;

                if (Convert.ToInt32(com.ExecuteScalar()) > 0)
                {
                    MySqlDataReader myDr = com.ExecuteReader();
                    myDr.Read();
                    Session["userName"] = txtUserName.Text;
                    Response.Redirect("ShowSubject.aspx?userID='" + myDr["ID"] + "'");
                    txtCode.Text = "";
                    myDr.Close();
                }
                else
                {
                    Warning.Text = "用户名或密码错误";
                }
                con.Close();
            }
            else
            {
                Warning.Text = "验证码输入错误";
            }
        }
        private void ValidateSettings()
        {
            try
            {
                ProgramOptionsManager.ValidateOptions(_options);
            }
            catch (InvalidDataException exc)
            {
                ShowErrorAndQuit(exc);
            }

            try
            {
                MD5Class.Verify7ZipBinaries();
            }
            catch (InvalidSignException e)
            {
                // backup process is not breaked here
                // because this message should go in logs too
                // because this tool usually runned from scheduler
                Console.WriteLine(Translation.Current[541], e.Message);
            }
        }
Пример #20
0
 private static void showMd5OfPacker()
 {
     Console.WriteLine(_Md5OfPackerFormatString, Files.SevenZipPacker, MD5Class.GetFileMD5(Files.SevenZipPacker), Files.Packer7ZipExeMd5);
     Console.WriteLine(_Md5OfPackerFormatString, Files.SevenZipGPacker, MD5Class.GetFileMD5(Files.SevenZipGPacker), Files.Packer7ZipGExeMd5);
     Console.WriteLine(_Md5OfPackerFormatString, Files.SevenZipPackerDll, MD5Class.GetFileMD5(Files.SevenZipPackerDll), Files.Packer7ZipDllMd5);
 }
Пример #21
0
        public ActionResult Login(LoginModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            User user = null;

            using (ISession session = NHibertnateSession.OpenSession())
            {
                user = session.Query <User>().FirstOrDefault(u => u.Login == model.Login && u.Password == MD5Class.Calculate(model.Password).ToLower());
            }
            if (user != null)
            {
                FormsAuthentication.SetAuthCookie(model.Login, true);
                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                ModelState.AddModelError("", "Пользователя с таким логином и поролем нет");
            }

            return(View(model));
        }
Пример #22
0
        public static void Main(string[] args)
        {
            ImproveIt.InitInfrastructure(true);
            loadLocalization();

            processInternalArguments(args);

            if (!File.Exists(Files.ProfileFile))
            {
                showErrorAndCloseApplicationIn10Seconds(Translation.Current[582]);
            }

            if (!SingleInstance.FirstInstance)
            {
                showErrorAndCloseApplicationIn10Seconds(Translation.Current[583]);
            }

            try
            {
                MD5Class.Verify7ZipBinaries();
            }
            catch (InvalidSignException e)
            {
                showErrorAndCloseApplicationIn10Seconds(string.Format(Translation.Current[584], e.Message));
            }

            loadConfiguration();
            Controller controller = new Controller(_options);

            if (args != null && args.Length > 0)
            {
                if (!(args.Length == 1 && args[0] == SchedulerParameters.START_WITHOUT_MESSAGE))
                {
                    showErrorAndCloseApplicationIn10Seconds(Translation.Current[586]);
                }
            }
            else
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(showMessageFor10Seconds), Translation.Current[587]);
            }

            try
            {
                if (!_options.DontCareAboutSchedulerStartup && !_options.DontNeedScheduler)
                {
                    verifyStartupScriptAndFixIt();
                }

                Application.SetCompatibleTextRenderingDefault(false);

                using (WithTray tray = new WithTray(controller))
                {
                    if (!RunAsWinFormApp)
                    {
                        tray.TurnIntoHiddenMode();
                    }

                    Application.Run();
                }
            }
            catch (Exception unhandledException)
            {
                ImproveIt.ProcessUnhandledException(unhandledException);
            }
        }
Пример #23
0
        public DBFile SaveFile(IUser user, FileStream fs, string clientFileHash, DBDirectory dir)
        {
            //if not allready done create neccessary dirs
            CreatePath();

            DBFile dbf = new DBFile();

            //skip the file if its larger than 5 mbyte
            if(fs.Length > 1024*1024*5){
            dbf.Status = FileStatus.FileTooBig;
            return dbf;}

            //check wether the file exists or not
            if(File.Exists(_serverStoragePath+clientFileHash)){
            dbf.Status = FileStatus.FileAllreadyExists;
            return dbf;}

            //check if directory exists or not
            try{
            DataTable dt = _db.Select("SELECT id FROM directories " +
                                      "WHERE id = '"+dir.ID+"'");

            if(dt.Rows.Count < 1 && dir.ID != 0){
                dbf.Status = FileStatus.DirectoryNotExists;
                return dbf;
            }

            }catch(Exception e){
            Debug.WriteLine("Server: "+e.Message);
            dbf.Status = FileStatus.DatabaseProblem;
            return dbf;
            }

            //try to upload the file and write it locally
            try{
            FileStream lfs = File.Open(_serverStoragePath+clientFileHash, FileMode.CreateNew);
            BinaryReader br = new BinaryReader(fs);
            BinaryWriter bw = new BinaryWriter(lfs);

            while(br.BaseStream.Length != br.BaseStream.Position){
                bw.Write(br.ReadBytes(1024*1024*5));}

            bw.Close();
            br.Close();
            lfs.Close();
            fs.Close();
            }catch(Exception e){
            Debug.WriteLine("Server: "+e.Message);
            dbf.Status = FileStatus.FileUploadFailed;
            return dbf;
            }

            //check crc
            MD5Class md5 = new MD5Class(_serverStoragePath+clientFileHash);
            string hash = md5.GetHash();
            if(!clientFileHash.Equals(hash))
            {
            try{
            File.Delete(_serverStoragePath+clientFileHash);
            }catch{}
            dbf.Status = FileStatus.FileCRCFailed;
            return dbf;
            }

            //if everthing went just fine write it in the db
            try{
            FileInfo fi = new FileInfo(fs.Name);
            FileInfo local = new FileInfo(_serverStoragePath+hash);

            _db.Insert("INSERT INTO files (md5,filename,user,size,directory) " +
                       "VALUES ('"+hash+"','"+fi.Name+"','"+user.ID+"','"+local.Length+"','"+dir.ID+"')");

            dbf.Status = FileStatus.FileUploaded;
            dbf.Name = fi.Name;
            dbf.User = user.ID;

            DataTable dt = _db.Select("SELECT id FROM files " +
                                      "WHERE md5 = '"+hash+"'");

            if(dt != null && dt.Rows.Count == 1 && dt.Rows[0].ItemArray.Length == 1)
                dbf.ID = int.Parse(dt.Rows[0].ItemArray[0].ToString());
            else
                throw new Exception("File inserted, but hash not found?");

            return dbf;
            }catch(Exception e){
            Debug.WriteLine("Server: "+e.Message);
            dbf.Status = FileStatus.DatabaseProblem;
            return dbf;}
        }
Пример #24
0
        public JsonResult LoginCheck(string Name, string password, string checkres)
        {
            string pwd = MD5Class.UserMd5(password);

            if (checkres == "学生")
            {
                DAL.DALT_Base_Student dal     = new DAL.DALT_Base_Student();
                Model.T_Base_Student  student = dal.GetStu(Name);
                if (ifExist(Name, pwd, checkres))
                {
                    Session["UserName"] = student.Name;
                    Session["UserId"]   = student.Id;
                    Session["ClassId"]  = student.ClassId;

                    Session["UserLevel"] = 0;
                    if (student.IsBGB == 1 && student.IsKDB == 1)
                    {
                        Session["UserLevel"] = 3;
                    }
                    else if (student.IsBGB == 1)
                    {
                        Session["UserLevel"] = 2;
                    }
                    else if (student.IsKDB == 1)
                    {
                        Session["UserLevel"] = 1;
                    }


                    return(Json(new { code = 11, message = "登录成功" }, JsonRequestBehavior.AllowGet));
                }

                else
                {
                    return(Json(new { code = 3, message = "用户名或密码错误" }, JsonRequestBehavior.AllowGet));
                }
            }
            else if (checkres == "老师")
            {
                DAL.DALT_Base_Teacher dal     = new DAL.DALT_Base_Teacher();
                Model.T_Base_Teacher  teacher = dal.GetTea(Name);
                DAL.DALT_Base_Class   dal2    = new DAL.DALT_Base_Class();
                Model.T_Base_Class    cla     = new T_Base_Class();

                if (teacher.IsBZR == 1)
                {
                    cla = dal2.FindCla(teacher.Id);
                    Session["ClassId"] = cla.Id;
                }
                else
                {
                    Session["ClassId"] = 0;
                }

                if (ifExist(Name, pwd, checkres))
                {
                    Session["UserName"] = teacher.Name;
                    Session["UserId"]   = teacher.Id;

                    Session["UserLevel"] = 10;
                    if (teacher.IsBZR == 1)
                    {
                        Session["UserLevel"] = 11;
                    }

                    return(Json(new { code = 12, message = "登录成功" }, JsonRequestBehavior.AllowGet));
                }

                else
                {
                    return(Json(new { code = 3, message = "用户名或密码错误" }, JsonRequestBehavior.AllowGet));
                }
            }
            else
            {
                DAL.DALT_Base_Admin dal   = new DAL.DALT_Base_Admin();
                Model.T_Base_Admin  admin = dal.GetAdmin(Name);
                if (ifExist(Name, pwd, checkres))
                {
                    Session["UserId"] = admin.Id;
                    Session["Name"]   = admin.LoginName;
                    return(Json(new { code = 13, message = "登录成功" }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json(new { code = 3, message = "用户名或密码错误" }, JsonRequestBehavior.AllowGet));
                }
            }
        }