Parsing text file. F# C#.

, , F Sharp C Sharp. , IBM Lotus Domino , MS SQL.
: < > : < >. , , , . , , , .
, GUI C Sharp, , MS SQL F Sharp. , "", BackgroundWorker IterativeBackgroundWorker Don Syme Expert F# 3.0.
, , . , C# , F#, , C# , , F#. , - . " ", .
1. F#. ParseBackgroundWorker.
-, , F# dll namespace LibraryFSharp.ParceTxtFileKmis.
ParseBackgroundWorker BackgroundWorker, , .
, F# . , C# . , , : , , , DoWork. C# RunWorkerAsync(). ProgressChanged, ReportProgress.
, , RunWorkerCompleted. , , , .
Code
(* 15.01.2014.
1. Lotus Domino.
2. BackgroundWorker - IterativeBackgroundWorker,
Don Syme Expert F# 3.0.
3. , , ,
MSSQL.
4. with _ as err ->failwith err.Message -
*)
namespace LibraryFSharp.ParceTxtFileKmis
open System
open System.IO
open System.Text.RegularExpressions
open Microsoft.FSharp.Data.TypeProviders

open System.ComponentModel
open System.Windows.Forms
open System.Threading

//
exception ReadFileException of string

// C#
type Delegate = delegate of obj * System.EventArgs -> unit

//
type Record = {
mutable FIO_DR: string
mutable strComp: string
mutable numPolis: string
}

// SQL
type SqlConnection =
Microsoft.FSharp.Data.TypeProviders.SqlDataConnection<ConnectionString =
// @"Data Source=(LocalDB)\v11.0;Initial Catalog=KMIS;Integrated Security=True;
// Encrypt=False;TrustServerCertificate=False">
@"Data Source=(localdb)\Projects;Initial Catalog=KMIS;Integrated Security=True;Connect Timeout=30;Encrypt=False;
TrustServerCertificate=False">

// BackgroundWorker
type ParseBackgroundWorker(inpFileName : string, outFileName: string) =
class
let worker = new BackgroundWorker(WorkerReportsProgress = true, WorkerSupportsCancellation = true)

//
let completed= new Event<Delegate, System.EventArgs>()
let error= new Event<Delegate, System.EventArgs>()
let cancelled= new Event<Delegate, System.EventArgs>()
let progress= new Event<Delegate, System.EventArgs>()
let started= new Event<_>()

//
let predicat = @"field1:|field2:|field3:"
let repl str= Regex.Replace(str,predicat, "")
//
let mutable client = {FIO_DR = ""; strComp = ""; numPolis= ""}

//
let mutable flagStart = false
let mutable flagStop= false
//
let mutable j = 0

//
let readFile (fileName : string) =
try
fileName
|> File.ReadLines
|> Seq.filter(fun str -> Regex.IsMatch(str, predicat))
//|> Seq.map (funs -> Regex.Replace(s,predicat, ""))
|> Seq.toArray
with | _ -> raise (ReadFileException(" :" + inpFileName ))

// RunWorkerAsync()
do worker.DoWork.Add(fun args ->
// 렠 ࠠ
let data =
try
readFile inpFileName
with _ as err ->failwith err.Message

//
let sizeArrayRecord = data.Length/10
let arrayRecord: (string array) = Array.zeroCreate sizeArrayRecord

// data
let select =
let rec parse i =
if i < (data.Length - 1) then
if worker.CancellationPending then args.Cancel <- true
else
let percent = int ((float (i + 1) / float (data.Length - 1)) * 100.0)
worker.ReportProgress(percent)
//
match data.[i] with
| var1 whenvar1.Contains(@"field1:")-> client.FIO_DR<- data.[i]; flagStart <- true
| var1 whenvar1.Contains(@"field2:")-> client.strComp<- data.[i]
| var1 whenvar1.Contains(@"field3:")-> client.numPolis<- data.[i]; if (flagStart = true) then flagStop<- true
| _ -> () //printfn " "

// arrayRecord
if flagStart && flagStop then
//
let all= repl client.FIO_DR + " ;" + repl client.strComp + " ;" +repl client.numPolis
//
arrayRecord.[j]<- all
j <- j + 1
flagStart <- false
flagStop<- false
parse (i+1)
parse 0
arrayRecord

//
let nameFile = outFileName
tryFile.WriteAllLines(nameFile, select)
with _as err ->failwith err.Message

//
let db = SqlConnection.GetDataContext()

//
let rec writeDataBase i =
if i < j then
let percent = int ((float (i + 1) / float (j- 1)) * 200.0)
worker.ReportProgress(percent)
let newRecord = new SqlConnection.ServiceTypes.Clients(Id = i, Fio = arrayRecord.[i], Strax="www", Polis ="334")
db.Clients.InsertOnSubmit(newRecord)
try
db.DataContext.SubmitChanges()
if worker.CancellationPending then args.Cancel <- true
else
writeDataBase (i + 1)
// Up trigger Error
with _ as e -> failwith e.Message
writeDataBase 0
//
args.Result <- box "O.K."
)

// DoWork
do worker.RunWorkerCompleted.Add(fun args ->
if args.Cancelled then cancelled.Trigger(args.Error, System.EventArgs())
elif args.Error <> null then error.Trigger (args.Error, System.EventArgs())
else completed.Trigger (args.Result,System.EventArgs()))

//
do worker.ProgressChanged.Add(fun args ->
progress.Trigger (args.ProgressPercentage,System.EventArgs()))

//
[<CLIEvent>]
member x.WorkerCompleted = completed.Publish
[<CLIEvent>]
member x.WorkerCancelled = cancelled.Publish
[<CLIEvent>]
member x.WorkerError = error.Publish
[<CLIEvent>]
member x.ProgressChanged = progress.Publish
member x.Started = started.Publish

member x.RunWorkerAsync() = worker.RunWorkerAsync()
member x.CancelAsync() = worker.CancelAsync()

end
2. C# ParseTextFile Windows Forms Application.
. , ParseBackgroundWorker , F# .
Code

/* 15.01.2014 года.

 * 1. C# часть проекта Parsing Text File.

 * 2. Работа с GUI интерфесом пользователя.

 * 3. Рработа с клаасом ParseBackgroundWorker на стороне C#.

 */

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

using LibraryFSharp.ParceTxtFileKmis;

 

namespace ParseTextFile

{

    public partial class mainForm : Form

    {

        private ParseBackgroundWorker   lib;

        private OpenFileDialog          openFileDialog;

        private SaveFileDialog          saveFileDialog;

        private string                  inputFileName;

        private string                  outputFileName;

 

        public mainForm()

        {      

                InitializeComponent();

        }

 

        // Отмена работы

        public void handleCancelAsync(object sender, EventArgs e)

        {

            progress.Visible = false;

            label.Text = "Parsing canceled ...";

        }

 

        // Ошибка при выполнении класса IterativeBackgroundWorker

        public void handleError(object sender, EventArgs e)

        {

            progress.Visible = false;

            label.Text = "Error parsing ..";

        }

 

        // Завершение работы

        public void nandleComplete(object sender, EventArgs e)

        {

            progress.Visible = false;

            progress.Value = 0;

            label.Text = "O.K.";

        }

 

        // Отображение процесса выполнения

        public void handleProgrees(object sender, EventArgs e)

        {

            label.Text = "Processing ...";

            progress.Visible = true;

            progress.Value = (int)sender;

        }

 

        // Начало процесса выполнения задания

        private void startParseToolStripMenuItem_Click(object sender, EventArgs e)

        {

            try

            {

                //

                inputFileName = inpFileName.Text.Trim();

                outputFileName = outFileName.Text.Trim();

                if (String.IsNullOrEmpty(inputFileName)) throw new ArgumentNullException("Value", "Input File Name is null");

                if (String.IsNullOrEmpty(outputFileName)) throw new ArgumentNullException("Value", "Output File Name is null");

 

                // Создадим обьект класса ParseBackgroundWorke и обработчики событий в классе.

                lib = new LibraryFSharp.ParceTxtFileKmis.ParseBackgroundWorker(inputFileName, outputFileName);

                lib.ProgressChanged += handleProgrees;

                lib.WorkerCompleted += nandleComplete;

                lib.WorkerError += handleError;

                lib.WorkerCancelled += handleCancelAsync;    

 

                label.Text = "Read File ...";

                lib.RunWorkerAsync();

            }

            catch (Exception error)

            {

                MessageBox.Show(error.Message);

            }

        }

 

        // Выбор входного файла   

        private void openFileToolStripMenuItem_Click(object sender, EventArgs e)

        {

            openFileDialog = new OpenFileDialog();

            openFileDialog.InitialDirectory = "c:\\";

            openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

            openFileDialog.FilterIndex = 2;

            openFileDialog.RestoreDirectory = true;

 

            if (openFileDialog.ShowDialog() == DialogResult.OK)

            {

                inpFileName.Text = openFileDialog.FileName;

            }  

        }

 

        // Отмена задания

        private void stopParseToolStripMenuItem_Click(object sender, EventArgs e)

        {

            lib.CancelAsync();

        }

 

        // Exit

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)

        {

            System.Environment.Exit(0);

            Application.Exit();

        }

 

        // Выбор выходного файла

        private void writeFileToolStripMenuItem_Click(object sender, EventArgs e)

        {

            saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

            saveFileDialog.FilterIndex = 2;

            saveFileDialog.RestoreDirectory = true;

 

            if (saveFileDialog.ShowDialog() == DialogResult.OK)

            {

                outFileName.Text = saveFileDialog.FileName;

            }

        }

 

    }

}



Microsoft Visual Studio 2012 .
C , .
15.01.2014 .

© Argument Ltd, 2017 ,  : 8-921-215-45-70,   e-mail