Exemplo n.º 1
0
        private void lbButton14_Click(object sender, EventArgs e)
        {
            if (!led4.Active)
            {
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    writer      = new CsvWriter(saveFileDialog1.FileName);
                    led4.Active = true;
                    if (led1.Active)
                    {
                        SetButtonsActivate(true);
                    }
                    timer1.Interval = Convert.ToInt16(textBox2.Text);
                    counter         = 0;
                    saveFileDialog1.Dispose();

                    lbButton14.Label = "Close";
                }
            }
            else
            {
                writer.EndRecord();
                writer.Close();
                led4.Active = false;
                SetButtonsActivate(false);
                lbButton14.Label = "Save";
            }
        }
Exemplo n.º 2
0
        public void TestCSV()
        {
            var layout = RowLayout.CreateTyped(typeof(TestStruct));
            var t1     = new TestStruct();

            t1.Init(TimeSpan.MinValue);
            var t2 = new TestStruct();

            t2.Init(TimeSpan.MaxValue);
            var t3 = new TestStruct();

            t3.Init(DateTime.Now.TimeOfDay);
            var ms = new MemoryStream();
            var w  = new CsvWriter(layout, ms);

            w.Write(t1);
            w.Write(t2);
            w.Write(t3);
            w.Close();
            var ms2  = new MemoryStream(ms.ToArray());
            var r    = new CsvReader(layout, ms2);
            var list = r.ReadList <TestStruct>();

            Assert.AreEqual(3, list.Count);
            Assert.AreEqual(t1, list[0]);
            Assert.AreEqual(t2, list[1]);
            Assert.AreEqual(t3, list[2]);
        }
Exemplo n.º 3
0
        private void StopLogging()
        {
            // Don't do anything if logging is already in "stopped" state.
            // Otherwise it will get stuck in the WaitOne loop.
            if (_logging != 2)
            {
                // Ensure timer is in "idle" state before stopping it.
                // If logging = 0 "idle", set logging = 2 "stopped"
                // but don't let another thrad change logging at the same time.
                // If logging was not 0 "idle", wait until it is.
                while (Interlocked.CompareExchange(ref _logging, 2, 0) != 0)
                {
                    _loggingLock.WaitOne();
                }

                try
                {
                    // Disable the timer.
                    _timer.Enabled = false;

                    // Close the filestream if necessary.
                    _writer?.Close();

                    // TODO:  Close the DUT serial port.

                    // Update GUI.
                    toolStripStatusLabel1.Text = "Ready...";
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "ERROR");
                }
            }
        }
Exemplo n.º 4
0
 /// <summary>
 ///		Cierra un archivo si estaba abierto
 /// </summary>
 private void CloseFile(CsvWriter writer)
 {
     if (writer != null)
     {
         writer.Flush();
         writer.Close();
     }
 }
Exemplo n.º 5
0
    // method - public: writes out a unit intelligence's action set to the associated file //
    public void WriteOutBehaviors()
    {
        //Error handling
        if (unitIntelligenceScript == null)
        {
            throw new MissingReferenceException("'Unit Intelligence' instance not assigned. Please assign the file in the Inspector and try again.");
        }
        if (actionSetFile == null)
        {
            throw new MissingReferenceException("CSV file 'Action Set File' not assigned. Please assign the file in the Inspector and try again.");
        }
        filePath = AssetDatabase.GetAssetPath(actionSetFile); //Gets file path
        if (filePath == "")
        {
            throw new MissingReferenceException("CSV file 'Action Set File' could not be found.  Please assign a valid file in the Inspector and try again.");
        }
        if (filePath.Substring(filePath.Length - 3, 3) != "csv")
        {
            throw new MissingReferenceException("CSV file 'Action Set File' is not a valid .csv file.  Please assign a valid file in the Inspector and try again.");
        }

        //Reads, clears, then builds writer for file
        string[]  fileLines = File.ReadAllLines(filePath);
        string    tempPath  = filePath.Substring(0, filePath.Length - 4) + "_temp.csv";
        CsvWriter writer    = new CsvWriter(tempPath);

        //Writes header lines
        for (int i = 0; i < rowsToSkip; i++)
        {
            if (fileLines.Length <= rowsToSkip)
            {
                //TODO update to read from header lines
                writer.WriteRow(fileLines[i]);
            }
            else
            {
                writer.WriteRow(fileLines[i]);
            }
        }

        //Writes in action items
        string[] actions = FormatActionsToCsv(unitIntelligenceScript.GetActions());
        for (int j = 0; j < actions.Length; j++)
        {
            writer.WriteRow(actions[j]);
        }

        //Cleans up the writer and writes to the file
        writer.Close();
        if (File.Exists(filePath))
        {
            File.Delete(filePath);
        }
        File.Move(tempPath, filePath);
        File.Delete(tempPath);

        Debug.Log("Writing successful!");
    }
Exemplo n.º 6
0
        public void Close()
        {
            var stream = new MemoryStream();
            var writer = new CsvWriter(stream, Encoding.ASCII, 1024, false);

            writer.Close();
            stream.Close();

            writer.WriteField("Hello");
        }
Exemplo n.º 7
0
        public void close_calls_dispose()
        {
            var textWriter = new Mock <TextWriter>();

            textWriter.Protected().Setup("Dispose", true).Verifiable();

            var writer = new CsvWriter(textWriter.Object);

            writer.Close();

            textWriter.Verify();
        }
Exemplo n.º 8
0
        public void CloseTest()
        {
            using var memory = new MemoryStream();
            var writer = new CsvWriter(new StreamWriter(memory));

            writer.Close();

            Assert.Throws <ObjectDisposedException>(() =>
            {
                writer.Write("Eren", 16);
            });
        }
Exemplo n.º 9
0
    static void Main(string[] args)
    {
        var writer = new CsvWriter <Person>("Persons.csv");

        writer.AddFormatter <DateTime>(d => d.ToString("MM/dd/yyyy"));

        writer.WriteHeaders();
        writer.WriteRows(GetPersons());

        writer.Flush();
        writer.Close();
    }
        private async void test_t_Click(object sender, RoutedEventArgs e)
        {
            double[]      test_dis = new double[] { 0, 7.5, 15, -7.5, -15 }; //new int[] { 0, 0, 0, 0, 0, 0, 0 };
            List <double> list_dis = new List <double>();


            int[]      test_time = new int[] { 10, 50, 100, 150, 200 };//0.01 0,05 ,0.1,0.15
            List <int> list_time = new List <int>();

            string[] file_t = System.IO.Directory.GetFiles(@"C:\Users\S2\OneDrive\デスクトップ\研究室\音\ランダム5文字_女性\wav_音量", "*", System.IO.SearchOption.AllDirectories);

            System.Random r        = new System.Random();
            List <string> listtext = new List <string>();


            list_time.AddRange(test_time);

            for (int i = 0; i < test_time.Length; i++)
            {
                int rand_t = r.Next(list_time.Count);
                slice.Value    = list_time[rand_t];
                div_sl.Content = slice.Value / 1000;
                list_time.RemoveAt(rand_t);
                listtext.Add(div_sl.Content.ToString());
                listtext.Add("\r\n");


                list_dis.AddRange(test_dis);

                for (int j = 0; j < test_dis.Length; j++)
                {
                    int rand_d = r.Next(list_dis.Count);
                    distance.Value = list_dis[rand_d];
                    listtext.Add(distance.Value.ToString());
                    await Task.Delay(2500);   //あきらめた

                    string url = test_time_play(file_t[r.Next(file_t.Length)]);
                    listtext.Add(url.Substring(url.Length - 9, 5));

                    listtext.Add("\r\n");
                    list_dis.RemoveAt(rand_d);

                    await Task.Delay(4500);
                }
                using (var csv = new CsvWriter(@"C:\Users\S2\OneDrive\デスクトップ\研究室\子音と母音\jikanjiku.csv"))
                {
                    Console.Write(listtext);
                    csv.WriteRow(listtext);
                    csv.Close();
                }
                listtext = new List <string>();
            }
        }
        public void StopLogging()
        {
            if (!IsActive)
            {
                return;
            }

            FARLogger.Debug($"Stopping logging to {FileName}");
            StopCoroutine(coroutine);
            writer.Close();
            coroutine = null;
        }
Exemplo n.º 12
0
        public static void ExportCSV(string path, Guid pollId)
        {
            var poll = DataService.PerThread.ContentSet.OfType <Poll>().SingleOrDefault(x => x.Id == pollId);

            if (poll == null)
            {
                throw new BusinessLogicException("Указан неверный идентификатор голосования");
            }
            else
            {
                var bulletins = poll.Bulletins.OrderByDescending(x => x.Weight).ThenByDescending(x => x.Result).ThenBy(x => x.Id).ToList();
                using (var writer = new CsvWriter(path))
                {
                    writer.ValueSeparator = ';';
                    writer.WriteHeaderRecord("Номер бюллетеня", "Голос", "Вес");

                    foreach (var pollBulletin in bulletins)
                    {
                        if (pollBulletin.Weight.Equals(0))
                        {
                            writer.WriteDataRecord(pollBulletin.Id, "Голос делегирован", "-");
                        }
                        else
                        {
                            switch ((VoteOption)pollBulletin.Result)
                            {
                            case VoteOption.Yes:
                                writer.WriteDataRecord(pollBulletin.Id, "За", pollBulletin.Weight);
                                break;

                            case VoteOption.No:
                                writer.WriteDataRecord(pollBulletin.Id, "Против", pollBulletin.Weight);
                                break;

                            case VoteOption.NotVoted:
                                writer.WriteDataRecord(pollBulletin.Id, "Не голосовал", pollBulletin.Weight);
                                break;

                            case VoteOption.Refrained:
                                writer.WriteDataRecord(pollBulletin.Id, "Воздержался", pollBulletin.Weight);
                                break;

                            default:
                                writer.WriteDataRecord(pollBulletin.Id, "Неизвестно", pollBulletin.Weight);
                                break;
                            }
                        }
                    }
                    writer.Close();
                }
            }
        }
Exemplo n.º 13
0
        public void CsvWriter_Basic()
        {
            StringBuilder sb     = new StringBuilder();
            StringWriter  sw     = new StringWriter(sb);
            CsvWriter     writer = new CsvWriter(sw);

            writer.WriteLine(10, 20, 11.5, "Hello", "Hello,World", "Hello \"Cruel\" World", null);
            writer.WriteLine("End");
            writer.Close();

            Assert.Equal(
                @"10,20,11.5,Hello,""Hello,World"",""Hello """"Cruel"""" World"",
End
", sb.ToString());
        }
Exemplo n.º 14
0
 private void ButtonFolder_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         CsvWriter outCSV = new CsvWriter(tbOutputCSVFolder.Text);
         outCSV.WriteRecord("TYPE", "PATH", "FILENAME");
         RecurseFolder(tbFolder.Text, "\\", outCSV);
         outCSV.Close();
         if (MessageBox.Show("Complete! Would you like to open the file?", "Complete!", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
         {
             System.Diagnostics.Process.Start(tbOutputCSVFolder.Text);
         }
     }
     catch (Exception excp)
     {
         MessageBox.Show("Error: " + excp.Message);
     }
 }
        private async void test_Click(object sender, RoutedEventArgs e)
        {
            System.Random r        = new System.Random();
            List <string> listtext = new List <string>();

            double[]      test_dis = new double[] { 0, 7.5, 15, -7.5, -15 }; //new int[] { 0, 0, 0, 0, 0, 0, 0 };
            List <double> list_dis = new List <double>();

            list_dis.AddRange(test_dis);
            await Task.Delay(10000);

            for (int j = 0; j < 7; j++)
            {
                for (int i = 0; i < test_dis.Length; i++)
                {
                    int rand = r.Next(list_dis.Count);
                    distance.Value = list_dis[rand];


                    textBox.Text = string.Join("", rand_hiragana());
                    listtext.Add(textBox.Text);
                    listtext.Add(distance.Value.ToString("#;-#;0"));
                    listtext.Add("\r\n");
                    shin_boin_play();
                    await Task.Delay(7000);   //あきらめた

                    list_dis.RemoveAt(rand);
                }


                list_dis.AddRange(test_dis);
                using (var csv = new CsvWriter(@"C:\Users\S2\OneDrive\デスクトップ\研究室\子音と母音\hiragana.csv"))
                {
                    Console.Write(listtext);
                    csv.WriteRow(listtext);
                    csv.Close();
                }

                listtext = new List <string>();
            }
            listtext.Add("\r\n");
        }
Exemplo n.º 16
0
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         CsvWriter outCSV = new CsvWriter(tbOutputCSV.Text);
         outCSV.WriteRecord("TYPE", "PATH", "FILENAME");
         System.IO.Stream s       = new FileStream(tbZipFile.Text, FileMode.Open);
         String           zipName = tbZipFile.Text.Split('\\').Last();
         RecurseZip("\\" + zipName, s, outCSV);
         outCSV.Close();
         if (MessageBox.Show("Complete! Would you like to open the file?", "Complete!", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
         {
             System.Diagnostics.Process.Start(tbOutputCSV.Text);
         }
     }
     catch (Exception excp)
     {
         MessageBox.Show("Error: " + excp.Message);
     }
 }
        private FileContentResult BuildFormResultsCSV(List <string> leadingHeaders)
        {
            //debug
            Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " started");

            string includeParts = Request["includeParts"] as string;
            Dictionary <string, int> formPartMap = (Dictionary <string, int>)Session["formPartMap"];
            string formId = Request["formId"] as string;

            ExportModel exportModel = (ExportModel)Session["ExportModel"];
            int         iFormId     = Convert.ToInt32(formId);

            List <def_Forms> forms = new List <def_Forms>();

            if (iFormId == 0)
            {
                foreach (int?id in exportModel.formIds)
                {
                    forms.Add(formsRepo.GetFormById(Convert.ToInt32(id)));
                }
            }
            else
            {
                forms.Add(formsRepo.GetFormById(iFormId));
            }


            string    outpath = ControllerContext.HttpContext.Server.MapPath("../Content/formResults_" + System.DateTime.Now.Ticks + ".csv");
            Stream    stream  = new FileStream(outpath, FileMode.Create);
            CsvWriter writer  = new CsvWriter(stream);

            // Build a map of with all relevent itemVariable identifiers
            Dictionary <int, string> ivIdentifiersById = new Dictionary <int, string>();

            foreach (string leadingIdent in leadingHeaders)
            {
                int id = leadingIdent.StartsWith("FORMRESULT_") ? -1 - ivIdentifiersById.Count :
                         formsRepo.GetItemVariableByIdentifier(leadingIdent).itemVariableId;
                ivIdentifiersById.Add(id, leadingIdent);
            }
            int i = 0;
            Dictionary <int, List <string> > formIdentMap = new Dictionary <int, List <string> >();

            foreach (def_Forms form in forms)
            {
                List <string> map = new List <string>();
                // Use the formPartMap when its not empty.
                i = (formPartMap.Count() > 0) ? formPartMap[form.formId + " start"] : 0;
                foreach (def_Parts prt in formsRepo.GetFormParts(form))
                {
                    if (prt.identifier.Contains("Scores"))
                    {
                        continue;
                    }
                    if (includeParts[i++] == '1')
                    {
                        //formPartMap.Add(form.formId + " " + prt.partId + " ident start", ivIdentifiersById.Count());
                        foreach (def_Sections sctn in formsRepo.GetSectionsInPart(prt))
                        {
                            formsRepo.CollectItemVariableIdentifiersById(sctn, ivIdentifiersById);
                            foreach (def_Items item in formsRepo.GetAllItemsForSection(sctn))
                            {
                                map.AddRange(formsRepo.GetItemVariablesByItemId(item.itemId).Select(iv => iv.identifier).ToList());
                            }
                        }

                        Debug.WriteLine("Added more sections to ivIdentifiersById, form: " + form.formId + " part: " + prt.partId + " new Count: " + ivIdentifiersById.Count());
                        //formPartMap.Add(form.formId + " " + prt.partId + " ident end", ivIdentifiersById.Count());
                    }
                }
                formIdentMap.Add(form.formId, map);
            }

            //add additional columns for any unhandled data the comes back from CommonExport.GetFormResultValues
            foreach (FormResultExportTagName tagName in Enum.GetValues(typeof(FormResultExportTagName)))
            {
                string header = "FORMRESULT_" + tagName.ToString();
                if (!ivIdentifiersById.Values.Contains(header))
                {
                    int id = -1 - ivIdentifiersById.Count; //not used, but must be unique to act as dictionary key
                    ivIdentifiersById.Add(id, header);
                }
            }

            //debug
            Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " finished Build a map of with all column identifiers");

            // Build a list of formresults to export
            List <int?>            formResultIds = exportModel.formResultIds;
            List <def_FormResults> formResultsToExport;

            if (iFormId == 0)
            {
                formResultsToExport = new List <def_FormResults>();
                foreach (def_Forms form in forms)
                {
                    formResultsToExport.AddRange(formsRepo.GetFormResultsByFormId(form.formId).Where(r => formResultIds.Contains(r.formResultId)).ToList());
                }
            }
            else
            {
                if (formResultIds == null)
                {
                    formResultsToExport = formsRepo.GetFormResultsByFormId(iFormId).ToList();
                }
                else
                {
                    formResultsToExport = formsRepo.GetFormResultsByFormId(iFormId).Where(r => formResultIds.Contains(r.formResultId)).ToList();
                }
            }
            Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " finished building a list of formresults to export");

            //build a header record with identifiers
            int           n           = ivIdentifiersById.Count;
            List <int>    ivIds       = new List <int>();
            List <string> identifiers = new List <string>();
            List <string> headerText  = new List <string>();
            int           j           = 0;

            foreach (KeyValuePair <int, string> de in ivIdentifiersById)
            {
                ivIds.Add(de.Key);
                identifiers.Add(de.Value);
                headerText.Add(de.Value.Replace("FORMRESULT_", ""));
                j++;
            }
            HeaderRecord hr = new HeaderRecord(true, headerText);

            writer.WriteRecord(hr);
            Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " finished build a header record with identifiers");

            //Build a DataRecord with item labels (second row in the output file)
            string[] values = new string[n]; //used to temporarily store the values for each row in the export
            for (int k = 0; k < n; k++)
            {
                if (identifiers[k].StartsWith("FORMRESULT_"))
                {
                    FormResultExportTagName tag = (FormResultExportTagName)Enum.Parse(typeof(FormResultExportTagName), headerText[k]);
                    values[k] = getCSVSecondRowLabelForFormResultTagName(tag);
                }
                else
                {
                    values[k] = formsRepo.GetItemVariableById(ivIds[k]).def_Items.label;
                }
            }
            writer.WriteRecord(new DataRecord(hr, values));
            Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " finished Build a DataRecord with item labels");

            //insert access logs (one for each assessment being exported)
            int[] arrFrIds = formResultIds.Where(id => id.HasValue).Select(id => id.Value).ToArray();
            AccessLogging.InsertMultipleAccessLogRecords(formsRepo, arrFrIds, (int)AccessLogging.accessLogFunctions.EXPORT, "Export CSV of assessment");

            // Build a DataRecord for each form result
            int count = 0, total = formResultsToExport.Count();

            foreach (def_FormResults fr in formResultsToExport)
            {
                //pull all necessary data for this formResult
                List <ValuePair> rspValues = CommonExport.GetDataByFormResultId(fr.formResultId);
                List <ValuePair> frValues  = CommonExport.GetFormResultValues(fr, forms.Where(f => f.formId == fr.formId).FirstOrDefault());

                //fill in values from formResult
                for (int k = 0; k < n; k++)
                {
                    if (identifiers[k].StartsWith("FORMRESULT_"))
                    {
                        //values[k] = GetFormResultValue(fr, headerText[k]);
                        ValuePair vp = frValues.Where(vpt => vpt.identifier == headerText[k]).FirstOrDefault();
                        if (vp != null)
                        {
                            values[k] = vp.rspValue;
                        }
                        else
                        {
                            values[k] = "";
                        }
                    }
                }

                //replace reponse values (numbers) with meaningful text for certain cells
                //FormResults_formStatus status;
                //Enum.TryParse(values[colIndex_status], out status);
                //values[colIndex_status] = status.ToString();
                //values[colIndex_sis_why] = GetDropdownText("assmtReason", values[colIndex_sis_why]);

                //fill in values from responseVariables
                for (i = 0; i < n; i++)
                {
                    if (identifiers[i].StartsWith("FORMRESULT_"))
                    {
                        continue;
                    }
                    ValuePair vp = null;
                    if (identifiers[i].StartsWith("FORMRESULT_") || formIdentMap[fr.formId].Contains(identifiers[i]))
                    {
                        vp = rspValues.Where(vpt => vpt.identifier == identifiers[i]).FirstOrDefault();
                    }
                    values[i] = vp == null ? "" : vp.rspValue;
                }
                writer.WriteRecord(new DataRecord(hr, values));

                //debug
                Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " finished " + (++count) + "/" + total + " records");
            }
            writer.Close(); //<- calls stream.Close()


            //debug
            Debug.WriteLine(" * * * BuildFormResultsCSV - " + DateTime.Now.Ticks + " finished everything");

            return(File(System.IO.File.ReadAllBytes(outpath), "text/csv", "results.csv"));
        }
 private void CleanUp()
 {
     writer.Close();
     stream.Close();
 }
Exemplo n.º 19
0
        public void close_calls_dispose()
        {
            var textWriter = new Mock<TextWriter>();
            textWriter.Protected().Setup("Dispose", true).Verifiable();

            var writer = new CsvWriter(textWriter.Object);
            writer.Close();

            textWriter.Verify();
        }