Ejemplo n.º 1
0
    public bool UpdateAlbum(int id, int owner_id, string name, DateTime creation_time, int album_size)
    {
        //int id, int owner_id, string name, DateTime creation_time, int album_size
        Album album = new Album(id, owner_id, name, creation_time, album_size);

        return(DBF.UpdateAlbum(album));
    }
Ejemplo n.º 2
0
 public static void Err(DBF l, string s)
 {
     if (showDebug[(int)l])
     {
         Log.Error("LWM." + l.ToString() + ": " + s);
     }
 }
Ejemplo n.º 3
0
 public static void Warn(DBF l, string s)
 {
     if (showDebug[(int)l])
     {
         Log.Warning("LWM." + l.ToString() + ": " + s);
     }
 }
Ejemplo n.º 4
0
        public void TestExcelExample1()
        {
            string pathExcel = Path.Combine(Environment.CurrentDirectory, "Data\\Example1.xlsx");
            string pathTemp  = TestLibrary.getTempFilename(".dbf");

            Xml_Form form  = generateForm();
            Excel    excel = new Excel();
            DBF      dbf   = new DBF(pathTemp, form.DBF);

            try
            {
                excel.OpenWorksheet(pathExcel);

                Work            work      = new Work(excel.worksheet, form, 120);
                Logger.LogLevel old_level = Logger.Level;
                Logger.SetLevel(Logger.LogLevel.TRACER);
                work.IterateRecords(dbf.appendRecord);
                Logger.SetLevel(old_level);
            }
            finally
            {
                dbf.close();
                excel.close();
            }
        }
Ejemplo n.º 5
0
 public Database()
 {
     //dbf = new DBFShow();
     dbf = new DBF();
     dbf.OpenFile("db.dbf");
     dbf.SetCodePage(201, 1251);
 }
Ejemplo n.º 6
0
 public static void Mess(DBF l, string s)
 {
     if (showDebug[(int)l])
     {
         Log.Message("LWM." + l.ToString() + ": " + s);
     }
 }
Ejemplo n.º 7
0
    public DataTable SelectEntireTable(string tableName)
    {
        DataTable dt  = new DataTable();
        string    sql = string.Format("select * from [{0}]", tableName.ToLower());

        dt           = DBF.selectFromTable(sql);
        dt.TableName = string.Format("{0}DataTable", tableName);
        return(dt);
    }
Ejemplo n.º 8
0
 public bool AddImage(int owner_id, int album_id, string name, string image_file_path)
 {
     try
     {
         Img img = new Img(1, owner_id, album_id, name, image_file_path);
         return(DBF.AddImage(img));
     }
     catch (Exception e) { throw e; }
 }
Ejemplo n.º 9
0
 public bool AddAlbum(int owner_id, string name)
 {
     try
     {
         // Album id doesn't matter since it is not considered in the AddAlbum function in DBF.
         Album al = new Album(1, owner_id, name);
         return(DBF.AddAlbum(al));
     }
     catch (Exception e) { throw e; }
 }
Ejemplo n.º 10
0
 public bool AdminAddUser(string name, string email, string password, DateTime birthday, bool isadmin)
 {
     try
     {
         // `id` doesn't matter in the DBF function AddUser because database gives id automatically.
         User u = new User(1, name, email, password, birthday, 0, isadmin);
         return(DBF.AddUser(u));
     }
     catch (Exception e) { throw e; }
 }
Ejemplo n.º 11
0
    public DataTable GetTableSchema(string tableName)
    {
        DataTable schema = DBF.GetTableSchema(tableName);

        if (schema != null)
        {
            schema.TableName = "dbSchema";
        }

        return(schema);
    }
Ejemplo n.º 12
0
        public void Startup()
        {
            Logger.SetLevel(Logger.LogLevel.DEBUG);

            encoding    = Encoding.UTF8;
            fields      = TestRepository.getFields();
            variables   = TestRepository.getVariables();
            dbfFileName = Path.GetTempFileName();

            dbf = new DBF(dbfFileName, fields, encoding);
            dbf.appendRecord(variables);
            Assert.AreEqual(dbf.Writed, 1);
            dbf.close();
        }
Ejemplo n.º 13
0
 public bool Signup(string name, string email, string password, DateTime birthday)
 {
     try
     {
         // `id` doesn't matter in the DBF function AddUser because database gives id automatically.
         User u      = new User(1, name, email, password, birthday);
         bool dpfRes = DBF.AddUser(u);
     }
     catch
     {
         return(false);
     }
     return(true);
 }
Ejemplo n.º 14
0
    public int GetAlbumIdByUserIdAndAlbumName(int ownerId, string albumName)
    {
        List <Album> albumList = DBF.GetAlbumsByName(albumName);

        if (albumList == null)
        {
            return(-1);
        }
        foreach (Album al in albumList)
        {
            if (al.AlbumOwnerId == ownerId)
            {
                return(al.AlbumId);
            }
        }
        return(-1);
    }
Ejemplo n.º 15
0
    public bool Login(string email, string password)
    {
        // This function should only be called after we verified the password and email length!
        if (!CheckPasswordLength(password))
        {
            Exception e = new Exception("Password Error");
            e.Data.Add("stringInfo", string.Format("Password Length must be longer than {0} and shorter than {1}!", Constants.MIN_PASSWORD_LENGTH, Constants.MAX_PASSWORD_LENGTH));
            throw e;
        }
        else if (!CheckEmailLength(email))
        {
            Exception e = new Exception("Email Error");
            e.Data.Add("stringInfo", string.Format("Email Length must be shorter than {0}!", Constants.MAX_EMAIL_LENGTH));
            throw e;
        }

        return(DBF.Login(email, password));
    }
Ejemplo n.º 16
0
    public DataTable GenerateSelectQueryAndFetchData(string tableName, string paramField, string searchParam, ParamAttrs attrs)
    {
        string paramWithMods = "";

        if (attrs.isBool)
        {
            paramWithMods = searchParam;
        }
        else if (attrs.isDate)
        {
            paramWithMods = string.Format("#{0}#", searchParam);
        }
        else if (attrs.isString)
        {
            paramWithMods = string.Format("\"{0}\"", searchParam);
        }

        string    query = string.Format("select * from [{0}] where {1}={2}", tableName, paramField, paramWithMods);
        DataTable res   = DBF.selectFromTable(query);

        res.TableName = "selectionResults";
        return(res);
    }
Ejemplo n.º 17
0
        /// <summary>
        /// Основной поток обработки
        /// </summary>
        /// <param name="obj">Форма процесса обработки, главная форма, список файлов для обработки</param>
        protected void delegate_action(object obj)
        {
            object [] data = (object[])obj;

            StatusWindow  window = (StatusWindow)data[0];
            MainWindow    wmain  = (MainWindow)data[1];
            List <string> files  = (List <string>)data[2];

            window.setState(true, "Подготовка файлов", 0, files.Count);

            wmain.Log(DataLog.LogImage.NONE, DateTime.Now.ToString("Начало конвертации dd.MM.yyyy в HH:mm:ss"));
            wmain.Log(DataLog.LogImage.NONE, "Директория: " + LastLaunch.Default.inputDirectory);
            wmain.Log(DataLog.LogImage.NONE, "Задано файлов для обработки: " + files.Count);

            if (config.only_rules)
            {
                CheckRules(files, window, wmain);
                return;
            }

            int   errcount    = 0;
            bool  reopenExcel = true;
            Excel excel       = null;
            DBF   dbf         = null;

            Stopwatch totalwatch = Stopwatch.StartNew();

            for (int idoc = 0; idoc < files.Count; idoc++)
            {
                string pathFull = files[idoc];
                string filename = Path.GetFileName(pathFull);
                string pathTemp = Path.GetTempFileName();

                bool deleteDbf = false;

                if (reopenExcel)
                {
                    excel       = new Excel();
                    reopenExcel = false;
                }

                try
                {
                    Logger.info("");
                    Logger.debug("");
                    Logger.debug("==============================================================");
                    Logger.info($"======= Загружаем Excel документ: {filename} ======");
                    Logger.debug("==============================================================");
                    window.updateState(true, $"Документ: {filename}", idoc);

                    excel.OpenWorksheet(pathFull);

                    var form = findCorrectForm(excel.worksheet, config);
                    if (form == null)
                    {
                        string warning = $"Для документа '{filename}' не найдено подходящих форм обработки!";
                        Logger.warn(warning);
                        wmain.Log(DataLog.LogImage.WARNING, warning);
                        throw new ArgumentNullException(warning);
                    }

                    string fileName   = getOutputFilename(excel.worksheet, pathFull, config.outfile.simple, config.outfile.script);
                    string pathOutput = Path.Combine(LastLaunch.Default.outputDirectory, fileName);

                    dbf = new DBF(pathTemp, form.DBF);

                    var total = excel.worksheet.UsedRange.Rows.Count - form.Fields.StartY;
                    window.setState(false, $"Обработано записей: {0}/{total}", 0, total);

                    Work     work    = new Work(form, config.buffer_size);
                    TimeSpan elapsed = work.IterateRecords(excel.worksheet, dbf.appendRecord,
                                                           id => window.updateState(false, $"Обработано записей: {id}/{total}", id)
                                                           );

                    dbf.close();

                    // Перемещение файла
                    if (File.Exists(pathOutput))
                    {
                        File.Delete(pathOutput);
                    }
                    File.Move(pathTemp, pathOutput);
                    Logger.debug($"Перемещение файла с {pathTemp} в {pathOutput}");

                    wmain.Log(
                        DataLog.LogImage.SUCCESS,
                        $"Документ '{filename}' в {dbf.Writed} строк успешно обработан за {elapsed:hh\\:mm\\:ss\\.ff}."
                        );
                    outlog.Add($"{filename} в {dbf.Writed} строк за {elapsed:hh\\:mm\\:ss\\.ff}");

                    Logger.info("Времени потрачено на обработку данных: " + elapsed);
                    Logger.info("Обработано записей: " + dbf.Writed);
                    Logger.debug($"Начиная с {form.Fields.StartY} по {form.Fields.StartY + dbf.Writed}");
                    Logger.info($"=============== Документ {Path.GetFileName(pathFull)} успешно обработан! ===============");
                }
                catch (Exception ex) when(!DEBUG)
                {
                    bool addToFormLog = true;

                    if (ex is COMException)
                    {
                        Logger.error("Excel вероятнее всего крашанулся, он будет перезапущен для следующего документа в очереди!");
                        reopenExcel = true;
                    }

                    if (ex is ThreadAbortException || ex.InnerException is ThreadAbortException)
                    {
                        Logger.warn($"Пользователь вышел во время процесса конвертации документа '{filename}'!");
                        goto skip_error_msgbox;
                    }

                    if (ex is ArgumentNullException)
                    {
                        if (!config.no_form_is_error)
                        {
                            continue;
                        }
                        addToFormLog = false;
                    }

                    if (addToFormLog)
                    {
                        wmain.Log(DataLog.LogImage.ERROR, $"Документ '{filename}' был пропущен из-за ошибки!\n{ex.Message}");
                    }
                    Logger.error($"Документ {filename} был пропущен из-за ошибки:\n{ex.Message}\n\n{ex.StackTrace}");

skip_error_msgbox:
                    errcount++;
                    deleteDbf = true;
                }
                finally
                {
                    Logger.debug("Закрытие COM Excel и DBF");
                    dbf?.close();
                    if (deleteDbf)
                    {
                        dbf?.delete();
                    }
                }
            }
            totalwatch.Stop();

            // Не забываем завершить Excel
            excel.close();

            string msgTotal = $"\nВремени затрачено суммарно: {totalwatch.Elapsed:hh\\:mm\\:ss\\.ff}";

            wmain.Log(DataLog.LogImage.INFO, msgTotal);
            Logger.info(msgTotal);

            if (errcount > 0)
            {
                wmain.Log(DataLog.LogImage.ERROR, config.warning ?? "{0}");
            }

            wmain.toggleConvertButton(true);
            updateDirectory();
            wmain.BeginInvoke((MethodInvoker)wmain.fillElementsData);
            window.mayClose();
        }
Ejemplo n.º 18
0
 public Album GetAlbumById(int albumId)
 {
     return(DBF.GetAlbumById(albumId));
 }
Ejemplo n.º 19
0
 public bool DeleteImage(Img image)
 {
     return(DBF.DeleteImage(image));
 }
Ejemplo n.º 20
0
 public bool DeleteAlbumImages(Album album)
 {
     return(DBF.DeleteImagesFromAlbum(album.AlbumId));
 }
Ejemplo n.º 21
0
 public bool DeleteAlbum(Album album)
 {
     return(DBF.DeleteAlbum(album));
 }
Ejemplo n.º 22
0
 public bool UpdateImage(Img updatedImage)
 {
     // int id, int owner_id, int album_id, string name, DateTime creation_time, string file_path // new Img(id, owner_id, album_id, name, creation_time, file_path
     return(DBF.UpdateImage(updatedImage));
 }
Ejemplo n.º 23
0
 public User GetUserObj(string email)
 {
     return(DBF.GetUserByEmail(email));
 }
Ejemplo n.º 24
0
 public List <Img> GetAlbumImages(int albumId)
 {
     return(DBF.GetAlbumImagesById(albumId));
 }
Ejemplo n.º 25
0
 public List <Album> GetUserAlbums(int userId)
 {
     return(DBF.GetUserAlbumsById(userId));
 }