private void OnRaiseStreamEvent(object sender, StreamEventArgs e)
        {
            // only notify if estimated process-time > notifier intervall
            bool notifierEnable = ((double)Properties.Settings.Default.notifierMessageProgressInterval < VisuGCode.gcodeMinutes);

            if (isStreaming)
            {
                updateProgressBar(e.CodeProgress, e.BuffProgress);
                if (notifierEnable && Properties.Settings.Default.notifierMessageProgressEnable)
                {
                    if ((elapsed.Seconds % (int)(60 * Properties.Settings.Default.notifierMessageProgressInterval)) == 5) // offset 5 sec. to get message at start
                    {
                        if (notifierUpdateMarker)
                        {
                            notifierUpdateMarker = false;
                            string etime = string.Format("{0:00}:{1:00} hrs", elapsed.Hours, elapsed.Minutes);
                            string msg   = string.Format("{0}Duration   : {1} \r\nCode line  : {2,6}\r\nProcessed: {3,4:0.0} %\r\nGrbl Buffer: {4,3:0} %\r\nTime stamp: {5}", "", etime, e.CodeLineSent, e.CodeProgress, e.BuffProgress, getTimeStampString());//Properties.Settings.Default.notifierMessageProgress
                            if (Properties.Settings.Default.notifierMessageProgressTitle)
                            {
                                Notifier.sendMessage(msg, string.Format("{0,4:0.0} %", e.CodeProgress));
                            }
                            else
                            {
                                Notifier.sendMessage(msg);
                            }
                        }
                    }
                    else
                    {
                        notifierUpdateMarker = true;
                    }
                }
            }

            int actualCodeLine = e.CodeLineSent;

            if (actualCodeLine < 0)
            {
                actualCodeLine = 0;
            }
            if (e.CodeLineSent > fCTBCode.LinesCount)
            {
                actualCodeLine = fCTBCode.LinesCount - 1;
            }
            fCTBCode.Selection = fCTBCode.GetLine(actualCodeLine);

            fCTBCodeClickedLineNow = e.CodeLineSent - 1; // - 1;
            fCTBCodeMarkLine();                          // set Bookmark and marker in 2D-View
//            fCTBCode.DoCaretVisible();

            try {
                if (this.fCTBCode.InvokeRequired)
                {
                    this.fCTBCode.BeginInvoke((MethodInvoker) delegate() { this.fCTBCode.DoCaretVisible(); });
                }
                else
                {
                    this.fCTBCode.DoCaretVisible();
                }
            } catch (Exception er)  {
                Logger.Error(er, "OnRaiseStreamEvent fCTBCode.InvokeRequired ");
            }


            if (_diyControlPad != null)
            {
                _diyControlPad.sendFeedback("[" + e.Status.ToString() + "]");
            }

            if (Properties.Settings.Default.guiProgressShow)
            {
                VisuGCode.ProcessedPath.processedPathLine(e.CodeLineConfirmed);
            }

            if (logStreaming)
            {
                Logger.Trace("OnRaiseStreamEvent  {0}  line {1} ", e.Status.ToString(), e.CodeLineSent);
            }

            switch (e.Status)
            {
            case grblStreaming.lasermode:
                showLaserMode();
                break;

            case grblStreaming.reset:
                flagResetOffset = true;
                stopStreaming(false);
                if (e.CodeProgress < 0)
                {
                    setInfoLabel(_serial_form.lastError, Color.Fuchsia);
                }
                else
                {
                    setInfoLabel("Vers. " + _serial_form.grblVers, Color.Lime);
                }
                statusStripClear(1, 2, "grblStreaming.reset");
                toolTip1.SetToolTip(lbInfo, lbInfo.Text);
                timerUpdateControls = true; timerUpdateControlSource = "grblStreaming.reset";    //updateControls();
                if (_coordSystem_form != null)
                {
                    _coordSystem_form.showValues();
                }

                ControlPowerSaving.EnableStandby();
                VisuGCode.ProcessedPath.processedPathClear();
                break;

            case grblStreaming.error:
                Logger.Info("streaming error at line {0}", e.CodeLineConfirmed);
                statusStripSet(0, grbl.lastMessage, Color.Fuchsia);
                pbFile.ForeColor = Color.Red;

                int errorLine = e.CodeLineConfirmed - 1;
                if (isStreamingCheck)
                {
                    errorLine = e.CodeLineConfirmed - 2;
                }
                ErrorLines.Add(errorLine);
                markErrorLine(errorLine);

                setInfoLabel(Localization.getString("mainInfoErrorLine") + errorLine.ToString(), Color.Fuchsia);

                fCTBCode.BookmarkLine(actualCodeLine - 1);
                fCTBCode.DoSelectionVisible();

                if (notifierEnable)
                {
                    Notifier.sendMessage(string.Format("Streaming error at line {0}\r\nTime stamp: {1}", e.CodeLineConfirmed, getTimeStampString()), "Error");
                }
                break;

            case grblStreaming.ok:
                if (!isStreamingCheck)
                {
                    if (grbl.lastErrorNr <= 0)
                    {
                        setInfoLabel(lblInfoOkString + "(" + (e.CodeLineSent + 1).ToString() + ")", Color.Lime);

                        signalPlay = 0;
                        btnStreamStart.BackColor = SystemColors.Control;
                    }
                }
                break;

            case grblStreaming.finish:
                Logger.Info("streaming finished ok {0}", isStreamingOk);
                if (isStreamingOk)
                {
                    if (isStreamingCheck)
                    {
                        setInfoLabel(Localization.getString("mainInfoFinishCheck"), Color.Lime);
                    }                                                                                    // "Finish checking G-Code"; }
                    else
                    {
                        setInfoLabel(Localization.getString("mainInfoFinishSend"), Color.Lime);
                    }                                                                                   // "Finish sending G-Code"; }
                }
                MainTimer.Stop();
                MainTimer.Start();
                timerUpdateControls = true; timerUpdateControlSource = "grblStreaming.finish"; //updateControls();
                saveStreamingStatus(0);
                showPicBoxBgImage           = false;                                           // don't show background image anymore
                pictureBox1.BackgroundImage = null;
                resetStreaming();

                if (notifierEnable && !notifierUpdateMarkerFinish)        // just notify once
                {
                    notifierUpdateMarkerFinish = true;
                    string msg = string.Format("{0}\r\nDuration  : {1} (hh:mm:ss)\r\nCode line : {2}\r\nTime stamp: {3}", Properties.Settings.Default.notifierMessageFinish, elapsed.ToString(@"hh\:mm\:ss"), fCTBCode.LinesCount, getTimeStampString());
                    if (Properties.Settings.Default.notifierMessageProgressTitle)
                    {
                        Notifier.sendMessage(msg, "100 %");
                    }
                    else
                    {
                        Notifier.sendMessage(msg);
                    }
                }
                break;

            case grblStreaming.waitidle:
                //          timerUpdateControls = true; timerUpdateControlSource = "grblStreaming.waitidle";//updateControls();// true);
                btnStreamStart.Image = Properties.Resources.btn_play;
                setInfoLabel(Localization.getString("mainInfoWaitIdle") + e.CodeLineSent.ToString() + ")", Color.Yellow);
                break;

            case grblStreaming.pause:
                //          lock (this)       2020-12-15 removed
            {
                signalPlay = 1;
                setInfoLabel(Localization.getString("mainInfoPause") + e.CodeLineSent.ToString() + ")", Color.Yellow);
                btnStreamStart.Image = Properties.Resources.btn_play;
                isStreamingPause     = true;
                MainTimer.Stop();
                MainTimer.Start();
                timerUpdateControls = true; timerUpdateControlSource = "grblStreaming.pause";        //updateControls(true);

                saveStreamingStatus(e.CodeLineSent);

                if (Properties.Settings.Default.flowControlEnable)         // send extra Pause-Code in MainTimer_Tick from Properties.Settings.Default.flowControlText
                {
                    delayedSend = 2;
                }

                if (logStreaming)
                {
                    Logger.Trace("OnRaiseStreamEvent - pause: {0}  in line:{1}", fCTBCode.Lines[fCTBCodeClickedLineNow], fCTBCodeClickedLineNow);
                }

                if (fCTBCode.Lines[fCTBCodeClickedLineNow].Contains("M0") && fCTBCode.Lines[fCTBCodeClickedLineNow].Contains("Tool"))          // keyword set in gcodeRelated 1132
                {
                    signalShowToolExchangeMessage = true; if (logStreaming)
                    {
                        Logger.Trace("OnRaiseStreamEvent trigger ToolExchangeMessage");
                    }
                }
                else
                {
                    if (notifierEnable)
                    {
                        Notifier.sendMessage("grbl Pause", "Pause");
                    }
                }
                //  if (Properties.Settings.Default.importGCToolChangeCode.Length > 1)
                //  {   processCommands(Properties.Settings.Default.importGCToolChangeCode); }
            }
            break;

            case grblStreaming.toolchange:
                timerUpdateControls  = true; timerUpdateControlSource = "grblStreaming.toolchange";   // updateControls();
                btnStreamStart.Image = Properties.Resources.btn_play;
                setInfoLabel(Localization.getString("mainInfoToolChange"), Color.Yellow);
                cBTool.Checked = _serial_form.toolInSpindle;
                break;

            case grblStreaming.stop:
                timerUpdateControls = true; timerUpdateControlSource = "grblStreaming.stop";    // updateControls();
                setInfoLabel(Localization.getString("mainInfoStopStream") + e.CodeLineSent.ToString() + ")", Color.Fuchsia);

                if (Properties.Settings.Default.flowControlEnable)     // send extra Pause-Code in MainTimer_Tick from Properties.Settings.Default.flowControlText
                {
                    delayedSend = 2;
                }
                break;

            default:
                break;
            }

            lastLabelInfoText = lbInfo.Text;
            //          lbInfo.Text += overrideMessage;
            if (this.lbInfo.InvokeRequired)
            {
                this.lbInfo.BeginInvoke((MethodInvoker) delegate() { this.lbInfo.Text += overrideMessage; });
            }
            else
            {
                this.lbInfo.Text += overrideMessage;
            }
        }
Example #2
0
 public override void WriteErrorLine(string line)
 {
     ErrorLines.Add(line);
 }
Example #3
0
 /// <summary>
 /// Format the error lines of the AS4 Error into readable descriptions for each line.
 /// </summary>
 public string FormatErrorLines()
 {
     return(String.Join(
                "; ",
                ErrorLines.Select(l => $"{l.ErrorCode.GetString()} {l.ShortDescription} {l.Detail.GetOrElse(String.Empty)}")));
 }
Example #4
0
        /// <summary>
        /// Call this to load each file
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="maxCount"></param>
        public void ParseFile(
            string filename, int maxPass,
            CancellationToken cancellationToken,
            IProgress <Progress> progress
            )
        {
            var  progressValue = new Progress();
            var  fi = new FileInfo(filename);
            var  fileLength = fi.Length;
            long totalPassCount = 0, totalErrorCount = 0;
            var  provider = CultureInfo.InvariantCulture;
            var  done     = false;

#if OLDMODE
            // var lineCount = 0;
            // long bytesRead = 0;
            //var lines = File.ReadLines(filename);
            //var fileLineAtLastErrorLine = -100L; // this will help fix lines that got split somehow
            //todo - better error line merging
            foreach (var line1 in lines)

            {
#else
            var regexes = new[] { passRegex, errorRegex }
            ;
            int matchIndex;
            var fileSplitter = new FileSplitter(filename);
            var line1        = fileSplitter.Next(regexes, out matchIndex);
            do
            {
                var lineCount = fileSplitter.LineCount;
                var bytesRead = fileSplitter.BytesRead;
#endif

                cancellationToken.ThrowIfCancellationRequested();
                if ((lineCount & 511) == 0)
                {
                    progressValue.Message = String.Format(
                        "File parsing phase: {0}/{1} kb read ({2:F2}%), {3} lines read, {4} passes read, {5} errors read, {6} error lines",
                        bytesRead / 1024, fileLength / 1024,
                        bytesRead * 100.0 / fileLength,
                        lineCount,
                        totalPassCount,
                        totalErrorCount,
                        ErrorLines.Count
                        );
                    progress.Report(progressValue);
                }

                ++lineCount;
                bytesRead += line1.Length;
                var line = line1;

                while (!done && !String.IsNullOrEmpty(line))
                {
                    var passMatch = passRegex.Match(line);
                    var errMatch  = (!passMatch.Success)
                        ? errorRegex.Match(line)
                        : null;
                    if (passMatch.Success)
                    {
                        var pass  = Int32.Parse(passMatch.Groups["pass"].Value);
                        var frame = Int32.Parse(passMatch.Groups["frame"].Value);

                        uint offset;
                        if (
                            !UInt32.TryParse(passMatch.Groups["offset"].Value, NumberStyles.HexNumber, provider,
                                             out offset))
                        {
                            throw new Exception("Illegal format");
                        }

                        uint tick;
                        if (!UInt32.TryParse(passMatch.Groups["tick"].Value, NumberStyles.HexNumber, provider, out tick))
                        {
                            throw new Exception("Illegal format");
                        }

                        ulong errorCount;
                        if (
                            !UInt64.TryParse(passMatch.Groups["errors"].Value, out errorCount))
                        {
                            throw new Exception("Illegal format");
                        }

                        var passItem = new PassRecord(pass, frame, offset, tick, errorCount);
                        line = passRegex.Replace(line, "", 1);

                        // do this just before last pass to ensure we got all errors
                        if (Passes.Count >= maxPass)
                        {
                            done = true;
                        }
                        else
                        {
                            Passes.Add(passItem);
                            ++totalPassCount;
                        }
                    }
                    else if (errMatch != null && errMatch.Success)
                    {
                        var lastpass = Passes.LastOrDefault();
                        if (lastpass == null)
                        {
                            continue;
                        }

                        uint offset;
                        if (
                            !UInt32.TryParse(errMatch.Groups["offset"].Value, NumberStyles.HexNumber, provider,
                                             out offset))
                        {
                            throw new Exception("Illegal format");
                        }
                        uint read;
                        if (!UInt32.TryParse(errMatch.Groups["read"].Value, NumberStyles.HexNumber, provider, out read))
                        {
                            throw new Exception("Illegal format");
                        }
                        uint desired;
                        if (
                            !UInt32.TryParse(errMatch.Groups["desired"].Value, NumberStyles.HexNumber, provider,
                                             out desired))
                        {
                            throw new Exception("Illegal format");
                        }

                        var errorType = Error.ErrorTypes.Erase;
                        if (errMatch.Groups["type"].Value == "E")
                        {
                            errorType = Error.ErrorTypes.Erase;
                        }
                        //else if (passMatch.Groups["type"].Value == "W")
                        //    errorType = Error.ErrorTypes.Write;
                        else
                        {
                            throw new Exception("Illegal format");
                        }
                        lastpass.Errors.Add(new Error(lastpass, offset, read, desired, errorType));
                        totalErrorCount++;
                        line = errorRegex.Replace(line, "", 1);
                    }
#if OLDMODE
                    else
                    {
                        var isErrorLine = true; // assume this line will be an error
                        if (fileLineAtLastErrorLine == lineCount - 1 && ErrorLines.Count > 0)
                        {
                            // back to back, pull out
                            var tempLine = ErrorLines.Last() + line;
                            isErrorLine &= !passRegex.IsMatch(tempLine);
                            isErrorLine &= !errorRegex.IsMatch(tempLine);

                            if (!isErrorLine)
                            {
                                // pull last one out and test it
                                line = tempLine;
                                ErrorLines.RemoveAt(ErrorLines.Count - 1);
                            }
                        }

                        if (isErrorLine)
                        {
                            ErrorLines.Add(line);
                            line = "";
                        }
                        fileLineAtLastErrorLine = lineCount;
                    } // error line
                }     // while line not all used up
            }
#else
                } // while line not all used up
                line1 = fileSplitter.Next(regexes, out matchIndex);
            } while (!done && !String.IsNullOrEmpty(line1))
Example #5
0
        public async Task <IActionResult> GetFile()
        {
            try
            {
                var builder = new ConfigurationBuilder()
                              .SetBasePath(Directory.GetCurrentDirectory())
                              .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

                IConfigurationRoot configuration = builder.Build();
                var allCitDebtsLines             = new string[10000000];

                //  while (true)
                //{
                //  if (DateTime.Now.AddHours(3).ToShortTimeString() == "09:58:00 aM")
                // {


                //List<string> fileNames = new List<string>();
                //List<string[]> lstCloudFilesdata = new List<string[]>();


                CloudStorageAccount storageAccount = CloudStorageAccount.Parse($"{configuration["ConnectionString1"]}");
                CloudFileClient     fileClient     = storageAccount.CreateCloudFileClient();
                CloudFileShare      fileShare      = fileClient.GetShareReference("import");
                //looks for a file share in the cloud
                bool fileShareExists = await fileShare.ExistsAsync();

                if (fileShareExists)
                {
                    List <CloudFile>   lstCloudFiles = new List <CloudFile>();
                    CloudFileDirectory rootDir       = fileShare.GetRootDirectoryReference();

                    List <string> sl = new List <string>();

                    DeptResults       DeptResults = new DeptResults();
                    List <ErrorLines> ErrorLines  = new List <ErrorLines>();
                    ErrorLines        ErrorLine   = new ErrorLines();



                    string bigfilename = "CitizenDebts_1M_3Big.txt";
                    string fileName    = "CitizenDebts_1M_3.txt";
                    //"DEBTS_" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
                    CloudFile file      = rootDir.GetFileReference(fileName);
                    string    checkfile = bigfilename;
                    //if the file exists

                    bool asd = await file.ExistsAsync();

                    if (asd)
                    {
                        //adds new datasting array
                        sl = await ReadDataAsync(file);

                        if (sl is null)
                        {
                            //return NotFound(HttpStatusCode.NotFound + "\n" + "\nΣφάλμα\nΤο αρχείο δεν περιέχει σωστό αριθμό στηλών</b>");
                            Redirect(DeptResults.BillsCount = 0, DeptResults.NewUsers = 0, HttpStatusCode.NotFound.ToString(), null, "\n" + "\nΣφάλμα\nΤο αρχείο δεν περιέχει σωστό αριθμό στηλών</b>");
                        }
                    }
                    else
                    {
                        Redirect(DeptResults.BillsCount = 0, DeptResults.NewUsers = 0, HttpStatusCode.NotFound.ToString(), null, "\n" + "\nΣφάλμα\nΔεν βρέθηκε το αρχείο</b>");

                        // return NotFound(HttpStatusCode.NotFound+ "\n" + "\nΣφάλμα\nΔεν βρέθηκε το αρχείο</b>");
                    }

                    Console.WriteLine("File into List " + DateTime.Now.ToString());
                    //foreach (string y in sl)
                    //{ Console.WriteLine("From list new : " + y); };
                    string[] cols;

                    for (int i = sl.Count - 1; i >= 0; i--)
                    {
                        cols = sl.ElementAt(i).Split(';');
                        if (cols[0].Trim().Length != 10 || !cols[0].All(char.IsDigit))
                        {
                            ErrorLine.line         = i;
                            ErrorLine.ErrorMessage = "Σφάλμα Λάθος ΑΦΜ";
                            ErrorLine.LineString   = sl[i];
                            ErrorLines.Add(ErrorLine);
                            sl.RemoveAt(i);
                            continue;
                            //return NotFound(HttpStatusCode.NotFound + "\n" + "\nΣφάλμα Λάθος ΑΦΜ");}
                        }
                        if (cols[1].Trim().Length == 0)
                        {
                            ErrorLine.line         = i;
                            ErrorLine.ErrorMessage = "Σφάλμα Λάθος Όνομα ";
                            ErrorLine.LineString   = sl[i];
                            ErrorLines.Add(ErrorLine);
                            sl.RemoveAt(i);     //return NotFound(HttpStatusCode.NotFound + "\n" + "\nΣφάλμα Λάθος Όνομα ");
                        }

                        if (cols[2].Trim().Length == 0)
                        {
                            ErrorLine.line         = i;
                            ErrorLine.ErrorMessage = "Σφάλμα Λάθος Επώνυμο ";
                            ErrorLine.LineString   = sl[i];
                            ErrorLines.Add(ErrorLine);
                            sl.RemoveAt(i);
                        }

                        if (cols[3].Trim().Length == 0 || !Regex.IsMatch(cols[3], @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
                        {
                            ErrorLine.line         = i;
                            ErrorLine.ErrorMessage = "Σφάλμα Λάθος Email   ";
                            ErrorLine.LineString   = sl[i];
                            ErrorLines.Add(ErrorLine);
                            sl.RemoveAt(i);
                        }

                        if (cols[4].Trim().Length == 0 || !cols[4].All(char.IsDigit))
                        {
                            ErrorLine.line         = i;
                            ErrorLine.ErrorMessage = "Σφάλμα Λάθος Τηλέφωνο  ";
                            ErrorLine.LineString   = sl[i];
                            ErrorLines.Add(ErrorLine);
                            sl.RemoveAt(i);
                        }

                        if (cols[5].Trim().Length == 0)
                        {
                            ErrorLine.line         = i;
                            ErrorLine.ErrorMessage = "Σφάλμα Λάθος Διεύθυσνη ";
                            ErrorLine.LineString   = sl[i];
                            ErrorLines.Add(ErrorLine);
                            sl.RemoveAt(i);
                        }

                        if (cols[6].Trim().Length == 0)
                        {
                            sl.RemoveAt(i); return(NotFound(HttpStatusCode.NotFound + "\n" + "\nΣφάλμα Λάθος Περιοχή "));
                        }
                        //!Regex.IsMatch(cols[7], @"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$")
                        if (cols[7].Trim().Length == 0)
                        {
                            ErrorLine.line         = i;
                            ErrorLine.ErrorMessage = "Σφάλμα Λάθος Αρ.Λογαριασμού ";
                            ErrorLine.LineString   = sl[i];
                            ErrorLines.Add(ErrorLine);
                            sl.RemoveAt(i);
                        }

                        if (cols[8].Trim().Length == 0)
                        {
                            ErrorLine.line         = i;
                            ErrorLine.ErrorMessage = "Σφάλμα Λάθος Περιγραφή Λογαριασμού";
                            ErrorLine.LineString   = sl[i];
                            ErrorLines.Add(ErrorLine);
                            sl.RemoveAt(i);
                        }

                        decimal number;
                        if (cols[9].Trim().Length == 0 || !Decimal.TryParse(cols[9], out number) || cols[9].Contains('.'))

                        {
                            ErrorLine.line         = i;
                            ErrorLine.ErrorMessage = "Σφάλμα Λάθος Ποσό";
                            ErrorLine.LineString   = sl[i];
                            ErrorLines.Add(ErrorLine);
                            sl.RemoveAt(i);
                        }

                        DateTime d;
                        if (cols[10].Trim().Length == 0 || !DateTime.TryParseExact(cols[10], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out d))
                        {
                            ErrorLine.line         = i;
                            ErrorLine.ErrorMessage = "Σφάλμα Λάθος Ημερομηνία";
                            ErrorLine.LineString   = sl[i];
                            ErrorLines.Add(ErrorLine);
                            sl.RemoveAt(i);
                        }
                    }



                    IEnumerable <CitizenDepts> o = from eachLine in (
                        from inner in sl
                        select inner.Split(';')
                        )

                                                   select new CitizenDepts
                    {
                        VAT              = eachLine[0],
                        FirstName        = eachLine[1],
                        LastName         = eachLine[2],
                        Email            = eachLine[3],
                        Phone            = eachLine[4],
                        Address          = eachLine[5],
                        County           = eachLine[6],
                        BillId           = eachLine[7],
                        Bill_description = eachLine[8],
                        //Amount = Decimal.Parse(eachLine[9]),
                        Amount  = Decimal.Parse(eachLine[9], System.Globalization.CultureInfo.GetCultureInfo("el-GR")),
                        DueDate = DateTime.ParseExact(eachLine[10],
                                                      "yyyyMMdd", CultureInfo.InvariantCulture)
                    };
                    Console.WriteLine("File splitted " + DateTime.Now.ToString());



                    var all = from c in _context.CitizenDepts select c;
                    _context.CitizenDepts.RemoveRange(all);
                    await _context.SaveChangesAsync();

                    Console.WriteLine("CitizenDept table deleted " + DateTime.Now.ToString());

                    foreach (var p in o)
                    {
                        _context.Add(p);
                    }
                    Console.WriteLine("Context filledup " + DateTime.Now.ToString());
                    await _context.SaveChangesAsync();



                    Console.WriteLine("Context saved to DB " + DateTime.Now.ToString());

                    //filter citizens
                    NewCitizens = o.
                                  Where(x => !((_context.ApplicationUser.Any(y => y.VAT == x.VAT)) || (_context.ApplicationUser.Any(y => y.Email == x.Email))))
                                  .Select(x => x).AsEnumerable();
                    Console.WriteLine("Citizens filterd " + DateTime.Now.ToString());


                    foreach (var p in NewCitizens)
                    {
                        Console.WriteLine(p.VAT + " , " + p.Email + " , " + p.LastName + " , " + p.Bill_description);
                    }
                    Console.WriteLine("Citizens log " + DateTime.Now.ToString());
                    //only new citizens

                    foreach (var p in NewCitizens.Distinct())
                    {
                        var user = new ApplicationUser {
                            UserName = p.Email, Email = p.Email
                        };

                        var TempPass = GeneratePassword(3, 3, 3, 3);
                        // int lowercase, int uppercase, int numerics, int symbols
                        Console.WriteLine(TempPass);
                        var result = await _userManager.CreateAsync(user, TempPass);

                        if (result.Succeeded)
                        {
                            if (checkfile != "CitizenDebts_1M_3.txt")
                            {
                                Console.WriteLine("Sending Emails");
                                SendMail(p.LastName, p.Email, TempPass);
                            }


                            var query =
                                from UserUpd in _context.ApplicationUser
                                where UserUpd.Email == p.Email
                                select UserUpd;

                            foreach (ApplicationUser UserUpd in query)
                            {
                                UserUpd.VAT       = p.VAT;
                                UserUpd.IsFirst   = true;
                                UserUpd.LastName  = p.LastName;
                                UserUpd.FirstName = p.FirstName;
                                UserUpd.Phone     = p.Phone;
                                UserUpd.County    = p.County;
                                UserUpd.Address   = p.Address;
                            }
                        }
                        else
                        {
                            Console.WriteLine("#############################ALREADY REGISTERED " + p.VAT + " , " + p.Email + " , " + p.LastName);
                        }
                        NewUsers++;
                    }
                    ;

                    await _context.SaveChangesAsync();

                    Console.WriteLine("New Users Registered and Emailed " + DateTime.Now.ToString());


                    foreach (var a in _context.ApplicationUser)
                    {
                        var query2 =
                            from UIdUpd in _context.CitizenDepts
                            where UIdUpd.VAT == a.VAT
                            select UIdUpd;

                        foreach (CitizenDepts UIdUpd in query2)
                        {
                            UIdUpd.UserGUId = a.Id;
                        }
                    }
                    ;

                    await _context.SaveChangesAsync();



                    List <Bills> NewBillsls = new List <Bills>();
                    Bills        NewBill    = new Bills();

                    List <CitizenDepts> UpdCit = new List <CitizenDepts>();


                    UpdCit.AddRange(_context.CitizenDepts);

                    foreach (var e in UpdCit)
                    {
                        Console.WriteLine("#############################CITIZEN_DEPTS " + e.VAT + " , " + e.Email + " , " + e.UserGUId);
                        NewBill.GuId             = e.BillId;
                        NewBill.Amount           = e.Amount;
                        NewBill.DueDate          = e.DueDate;
                        NewBill.Bill_description = e.Bill_description;
                        NewBill.Status           = 0;
                        NewBill.UserId           = e.UserGUId;
                        NewBill.PaymentMethodId  = 1;
                        NewBill.SettlementId     = 1;
                        NewBillsls.Add(NewBill);
                        NewBill = new Bills();
                    }

                    //....  delete bills
                    var allBills = from c in _context.Bills select c;
                    _context.Bills.RemoveRange(allBills);
                    await _context.SaveChangesAsync();

                    //....  delete settlements
                    _context.Settlements.RemoveRange(
                        _context.Settlements
                        .Where(s => s.ID != 1)
                        );
                    await _context.SaveChangesAsync();

                    _context.Bills.AddRange(NewBillsls);

                    await _context.SaveChangesAsync();

                    string Mes;
                    if (ErrorLines.Count() > 0)
                    {
                        Mes = "Ύπήρχαν " + ErrorLines.Count() + " σφάλματα στην εισαγωγή του αρχείου";
                    }
                    else
                    {
                        Mes = "Δεν Υπήρχαν Σφάλματα στην εισαγωγή του αρχείου";
                    }


                    //  return View(NewCitizens);
                    return(RedirectToAction("DeptResults", "DeptResults", new DeptResults
                    {
                        BillsCount = NewBillsls.Count(),
                        NewUsers = NewUsers,
                        HttpStatus = "",
                        ErrorLines = ErrorLines,
                        Message = Mes
                    }));
                }
                else
                {
                    return(NotFound(HttpStatusCode.NotFound + "\n" + "\nΔεν βρέθηκε ο κοινός φάκελος!"));
                }
            }
            catch (Exception ex)
            {
                return(NotFound(HttpStatusCode.ExpectationFailed + "\n" + ex.Message + "\nΣφάλμα\nΑπροσδιόριστο σφάλμα Στην Εισαγωγή του αρχείου</b>"));
            }
            finally
            {
                Console.WriteLine("Import Finished Successfully " + DateTime.Now.ToString());
            }

            return(View());
        }