protected override void OutBlock(ResModel resModel, IXAQuery query, CsvHelper.CsvWriter writer)
        {
            var szTrCode = resModel.Name;

            var block1 = resModel.Blocks[szTrCode + "OutBlock1"];

            writer.WriteHeader <_t9905OutBlock1>();
            for (var i = 0; i < query.GetBlockCount(szTrCode + "OutBlock1"); i++)
            {
                var result = new _t9905OutBlock1()
                {
                    shcode  = query.GetFieldData(block1.Name, "shcode", i),
                    expcode = query.GetFieldData(block1.Name, "expcode", i),
                    hname   = query.GetFieldData(block1.Name, "hname", i),
                };
                writer.NextRecord();
                writer.WriteRecord(result);
                Constants.CodeElwBases.Add(result.shcode, new CodeElwBase()
                {
                    Name         = result.hname,
                    Code         = result.shcode,
                    ExpandedCode = result.expcode,
                });
            }
        }
        protected override void OutBlock(ResModel resModel, IXAQuery query, CsvHelper.CsvWriter writer)
        {
            var szTrCode = resModel.Name;
            var block    = resModel.Blocks[szTrCode + "OutBlock"];

            writer.WriteHeader <_t9942OutBlock>();
            for (var i = 0; i < query.GetBlockCount(block.Name); i++)
            {
                var result = new _t9942OutBlock()
                {
                    hname   = query.GetFieldData(block.Name, "hname", i),
                    shcode  = query.GetFieldData(block.Name, "shcode", i),
                    expcode = query.GetFieldData(block.Name, "expcode", i),
                };
                writer.NextRecord();
                writer.WriteRecord(result);
                Constants.CodeElws.Add(result.shcode, new CodeElw()
                {
                    UnderlyingAssetsCategory = "",
                    UnderlyingAssetsCode     = "",
                    Name         = result.hname,
                    Code         = result.shcode,
                    ExpandedCode = result.expcode,
                });
            }
        }
Exemple #3
0
        public static void WriteCSV <T>(IEnumerable <T> simulationResults, string fileName)
        {
            var csvFilePath = Path.Combine(Directory.GetCurrentDirectory(), fileName);

            Console.WriteLine(csvFilePath);

            using (var fileStream = new FileStream(csvFilePath, FileMode.Create))
            {
                using (var writer = new StreamWriter(fileStream, Encoding.UTF8))
                {
                    using (var csvWriter = new CsvHelper.CsvWriter(writer))
                    {
                        csvWriter.WriteHeader <T>();
                        csvWriter.Flush();
                        writer.WriteLine();
                        writer.Flush();

                        foreach (var result in simulationResults)
                        {
                            csvWriter.WriteRecord(result);
                            csvWriter.Flush();
                            writer.WriteLine();
                            writer.Flush();
                        }
                    }
                }
            }
        }
        public IProfile Create(string profileName)
        {
            if (Exists(profileName))
            {
                throw new Core.Services.ProfileNameConflictException(profileName);
            }

            string       profilePath     = ProfilePath(profileName);
            FileInfoBase profileFileInfo = _fileSystem.FileInfo.FromFileName(profilePath);
            StreamWriter writer          = profileFileInfo.CreateText();

            using (CsvHelper.CsvWriter csvWriter = new CsvHelper.CsvWriter(writer, leaveOpen: false))
            {
                csvWriter.Configuration.QuoteAllFields = true;
                csvWriter.Configuration.RegisterClassMap(new CSV.MatchRecordConfiguration());

                csvWriter.WriteHeader <MatchRecord>();
                csvWriter.NextRecord();
            }

            FileSystemProfile profile = new FileSystemProfile(_fileSystem, profileName, profilePath);

            AddToCache(profileName, profile);
            return(profile);
        }
        private void button1_Click(object sender, EventArgs e)
        {
            List <Musteri> musterilerim = new List <Musteri>();

            for (int i = 0; i < 50; i++)
            {
                Musteri temp = new Musteri();
                temp.ID     = i;
                temp.Adi    = FakeData.NameData.GetFirstName();
                temp.Soyadi = FakeData.NameData.GetSurname();
                temp.Email  = $"{temp.Adi}.{temp.Soyadi}@{FakeData.NetworkData.GetDomain()}";

                temp.Tel = FakeData.PhoneNumberData.GetPhoneNumber();
                musterilerim.Add(temp);
            }


            if (!Directory.Exists("D:\\CSV\\Dosyam"))
            {
                Directory.CreateDirectory("D:\\CSV\\Dosyam");
            }
            StreamWriter sw = new StreamWriter("D:\\CSV\\Dosyam\\yeni", true);

            CsvHelper.CsvWriter writer = new CsvHelper.CsvWriter(sw);
            writer.WriteHeader(typeof(Musteri));

            foreach (Musteri item in musterilerim)
            {
                writer.WriteRecord(item);
            }
            sw.Close();

            MessageBox.Show("Tamamlandı");
        }
Exemple #6
0
        private void btnWrite_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog sfd = new SaveFileDialog()
            {
                Filter = "CSV|*.csv", ValidateNames = true
            })
            {
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    using (var sw = new StreamWriter(sfd.FileName))
                    {
                        var csvWriter = new CsvHelper.CsvWriter(sw);
                        csvWriter.WriteHeader(typeof(Student));
                        csvWriter.NextRecord();
                        // Method 1
                        //foreach (Student s in studentBindingSource.DataSource as List<Student>)
                        //{
                        //    csvWriter.WriteRecord(s);
                        //    csvWriter.NextRecord();
                        //}

                        // Method 2
                        foreach (Student s in studentBindingSource.List)
                        {
                            csvWriter.WriteRecord(s);
                            csvWriter.NextRecord();
                        }
                    }

                    MessageBox.Show("Your data has been successfully saved", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        protected override void OutBlock(ResModel resModel, IXAQuery query, CsvHelper.CsvWriter writer)
        {
            var szTrCode = resModel.Name;
            var block    = resModel.Blocks[szTrCode + "OutBlock"];

            writer.WriteHeader <_t8401OutBlock>();
            for (var i = 0; i < query.GetBlockCount(block.Name); i++)
            {
                var result = new _t8401OutBlock()
                {
                    hname    = query.GetFieldData(block.Name, "hname", i),
                    shcode   = query.GetFieldData(block.Name, "shcode", i),
                    expcode  = query.GetFieldData(block.Name, "expcode", i),
                    basecode = query.GetFieldData(block.Name, "basecode", i),
                };
                writer.NextRecord();
                writer.WriteRecord(result);
                Constants.CodeFutures.Add(result.shcode, new CodeFutures()
                {
                    UnderlyingAssetsCategory = "STOCK",
                    UnderlyingAssetsCode     = result.basecode,
                    Name         = result.hname,
                    Code         = result.shcode,
                    ExpandedCode = result.expcode,
                    //TODO Listing, Expirationdate
                    ListingDate    = "",
                    ExpirationDate = "",
                });
            }
        }
Exemple #8
0
        private static string WriteToFile(List <Tweet> tweets, string startDate, string endDate, string dataType)
        {
            var csvFilePath = $"/Users/{Environment.UserName}/Desktop/{dataType}_{startDate.ReplaceAll("/","-")}-{endDate.ReplaceAll("/", "-")}.csv".MapAbsolutePath();

            using (var writer = new StreamWriter(csvFilePath))
                using (var csv = new CsvHelper.CsvWriter(writer, CultureInfo.InvariantCulture))
                {
                    csv.WriteHeader <Tweet>();
                    csv.NextRecord();
                    foreach (var tweet in tweets)
                    {
                        Tweet extendedTweet = tweet;
                        extendedTweet.MediaData.ForEach(media =>
                        {
                            extendedTweet.MediaDataUrl     = media.url;
                            extendedTweet.MediaTitle       = media.title;
                            extendedTweet.MediaDescription = media.description;
                        });
                        extendedTweet.ReferencedTweets.ForEach(reference =>
                        {
                            extendedTweet.ReferencedTweetId   = reference.Id;
                            extendedTweet.ReferencedTweetType = reference.Type;
                        });

                        csv.WriteRecord(extendedTweet);
                        csv.NextRecord();
                    }
                }

            return(csvFilePath);
        }
Exemple #9
0
 private string processCsv(List <ExportInvoiceHolder> invoices)
 {
     using StringWriter writer = new StringWriter();
     using var csvWriter       = new CsvHelper.CsvWriter(writer, new CsvConfiguration(CultureInfo.InvariantCulture), true);
     csvWriter.WriteHeader <ExportInvoiceHolder>();
     csvWriter.NextRecord();
     csvWriter.WriteRecords(invoices);
     csvWriter.Flush();
     return(writer.ToString());
 }
Exemple #10
0
 private static string ProcessCsv(IEnumerable <ExportTransaction> invoices)
 {
     using StringWriter writer = new();
     using var csvWriter       = new CsvHelper.CsvWriter(writer, new CsvConfiguration(CultureInfo.InvariantCulture), true);
     csvWriter.Configuration.RegisterClassMap <ExportTransactionMap>();
     csvWriter.WriteHeader <ExportTransaction>();
     csvWriter.NextRecord();
     csvWriter.WriteRecords(invoices);
     csvWriter.Flush();
     return(writer.ToString());
 }
Exemple #11
0
 public void WriteAll(StreamWriter stream, IEnumerable <CityEvent> events)
 {
     using (var ww = new CsvHelper.CsvWriter(stream, _conf))
     {
         ww.WriteHeader <CityEvent>();
         foreach (var el in events)
         {
             ww.WriteRecord(el);
         }
     }
 }
Exemple #12
0
        private async Task <int> ExportDepositAddressesAsync(
            string settingsUrl)
        {
            #region RegisterDependencies

            var appSettings = _helper.GetCurrentSettingsFromUrl(settingsUrl);
            var(resolver, consoleLogger) = _helper.GetResolver(appSettings);

            #endregion

            string hotWalletAddress           = appSettings.CurrentValue.Ethereum.HotwalletAddress;
            var    transferContractRepository =
                (IErc223DepositContractRepository)resolver.ResolveKeyed(Constants.DefaultKey,
                                                                        typeof(IErc223DepositContractRepository));

            string continuationToken = null;

            await consoleLogger.WriteInfoAsync(nameof(ExportDepositAddressesAsync),
                                               "", $"Begin export");

            using (var writer = new StreamWriter("exportedDeposits.csv"))
                using (var csvWriter = new CsvHelper.CsvWriter(writer))
                {
                    csvWriter.WriteHeader <DepositRecord>();
                    csvWriter.NextRecord();

                    var record = new DepositRecord {
                        Address = hotWalletAddress
                    };
                    csvWriter.WriteRecord(record);
                    csvWriter.NextRecord();

                    do
                    {
                        var(collection, token) = await transferContractRepository.GetByTokenAsync(100, continuationToken);

                        continuationToken = token;

                        foreach (var depositContract in collection)
                        {
                            var newRecord = new DepositRecord {
                                Address = depositContract.ContractAddress
                            };
                            csvWriter.WriteRecord(newRecord);
                            csvWriter.NextRecord();
                        }
                    } while (!string.IsNullOrEmpty(continuationToken));
                }

            await consoleLogger.WriteInfoAsync(nameof(ExportDepositAddressesAsync),
                                               "", $"Export is completed");

            return(0);
        }
Exemple #13
0
        protected override void OutBlock(ResModel resModel, IXAQuery query, CsvHelper.CsvWriter writer)
        {
            var szTrCode = resModel.Name;
            var block    = resModel.Blocks[szTrCode + "OutBlock"];

            writer.WriteHeader <_t8424OutBlock>();
            for (var i = 0; i < query.GetBlockCount(block.Name); i++)
            {
                //LOG.Debug($"trCountLimit : {query.GetTRCountLimit(szTrCode)}, trCountRequest : {query.GetTRCountRequest(szTrCode)}, trCountBaseSec : {query.GetTRCountBaseSec(szTrCode)}, trCountPerSec : {query.GetTRCountPerSec(szTrCode)}");
                var result = new _t8424OutBlock()
                {
                    hname  = query.GetFieldData(block.Name, "hname", i),
                    upcode = query.GetFieldData(block.Name, "upcode", i),
                };
                writer.NextRecord();
                writer.WriteRecord(result);

                string category;
                switch (_inBlock.gubun1)
                {
                case "1":
                    category = "KOSPI";
                    break;

                case "2":
                    category = "KOSDAQ";
                    break;

                case "3":
                    category = "KRX";
                    break;

                case "4":
                    category = "ETC";
                    break;

                default:
                    category = "ALL";
                    //TODO error
                    break;
                }
                Constants.CodeSectors.Add(result.upcode, new CodeSector()
                {
                    Category = category,
                    Name     = result.hname,
                    Code     = result.upcode,
                });
            }
        }
Exemple #14
0
        public FileStreamResult GetEquivalencies()
        {
            var equivalencies = EquivalenceUnitSetsReader.DumpEquivalencies(this._db);
            var memory        = new MemoryStream();
            var writer        = new StreamWriter(memory, Encoding.UTF8);
            var csv           = new CsvHelper.CsvWriter(writer);

            csv.WriteHeader <EquivalenceUnitSetRow>();
            csv.NextRecord();
            csv.WriteRecords(equivalencies);
            csv.Flush();
            writer.Flush();
            memory.Seek(0, SeekOrigin.Begin);
            return(new FileStreamResult(memory, "text/csv"));
        }
        }     // end sub

        /// <summary>
        /// <para xml:lang="en">Output the names of properties of a object as header of a TSV file.</para>
        /// <para xml:lang="ja">TSVファイルヘッダとして、オブジェクトのプロパティの名前を出力します。</para>
        /// </summary>
        /// <typeparam name="T">
        /// <para xml:lang="en">The type of object to dump.</para>
        /// <para xml:lang="ja">ダンプするオブジェクトの型</para>
        /// </typeparam>
        /// <param name="target">
        /// <para xml:lang="en">
        /// The object whose properties names are read. However, those properties values are not outputted.
        /// Use DumpTsvRecord method, DumpTsv method or other methods to output values.
        /// </para>
        /// <para xml:lang="ja">
        /// プロパティの名前を読み取るオブジェクト。ただしプロパティの値は出力されません。
        /// 値を出力するには DumpTsvRecord メソッドやDumpTsvメソッドなどを使用します。
        /// </para>
        /// </param>
        /// <param name="name">
        /// <para xml:lang="en">The name which is used for a file.</para>
        /// <para xml:lang="ja">ファイルに使用される名前。</para>
        /// </param>
        /// <param name="format">
        /// <para xml:lang="en">
        /// The lambda expression which is used for choosing properties to dump.
        /// Set like <code>a=&gt;new {a.A, a.B}</code>  to dump A property and B property of the object.
        /// Set like <code>a=&gt;a</code>  to dump all properties of the object.
        /// </para>
        /// <para xml:lang="ja">
        /// ダンプするプロパティを選択するラムダ式。
        /// オブジェクトのAプロパティとBプロパティをダンプする場合には、<code>a=&gt;new {a.A, a.B}</code> のように指定します。
        /// 全てのプロパティをダンプする場合には<code>a=&gt;a</code>を指定します。
        /// </para>
        /// </param>
        public static void DumpTsvHeader <T>(T target, string name, Func <T, object> format)
        {
            Dumper.WriteTextFile(name, ".tsv", writer =>
            {
                var configuration = new CsvHelper.Configuration.Configuration {
                    Delimiter = "\t"
                };
                using (var tsv = new CsvHelper.CsvWriter(writer, configuration))
                {
                    var v = format(target);
                    tsv.WriteHeader(v.GetType());
                    tsv.NextRecord();
                } // end using (tsv)
            });
        }         // end sub
Exemple #16
0
        public static HttpResponseMessage Export <T>(List <T> list, Type classMapType, string fileName, bool hasHeader = true)
        {
            CsvHelper.Configuration.CsvConfiguration csvCommonConfiguration = new CsvHelper.Configuration.CsvConfiguration
            {
                Delimiter       = ",",
                HasHeaderRecord = hasHeader
            };

            MemoryStream ms      = new MemoryStream();
            StreamWriter swriter = new StreamWriter(ms, Encoding.GetEncoding("windows-1252"));
            var          csv     = new CsvHelper.CsvWriter(swriter, csvCommonConfiguration);

            csv.Configuration.RegisterClassMap(classMapType);
            if (hasHeader)
            {
                csv.WriteHeader <T>();
            }
            for (int i = 0; i < list.Count; i++)
            {
                try
                {
                    csv.WriteRecord(list[i]);
                }
                catch (Exception ex)
                {
                    #region Logging

                    if (logger.IsErrorEnabled)
                    {
                        logger.Error(string.Format("L'export de la ligne {0} a échoué", i), ex);
                    }

                    #endregion Logging
                }
            }

            //Flush du writer et remise à zéro du pointeur de lecture du stream
            swriter.Flush();
            ms.Position = 0;

            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StreamContent(ms);
            response.Content.Headers.ContentType                 = new MediaTypeHeaderValue("application/octet-stream");
            response.Content.Headers.ContentDisposition          = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = fileName;

            return(response);
        }
Exemple #17
0
        private void EnsureFileExists()
        {
            if (!_fileSystem.File.Exists(_csvPath))
            {
                FileInfoBase fileInfo = _fileSystem.FileInfo.FromFileName(_csvPath);
                StreamWriter writer   = fileInfo.AppendText();
                using (CsvHelper.CsvWriter csvWriter = new CsvHelper.CsvWriter(writer, leaveOpen: false))
                {
                    csvWriter.Configuration.QuoteAllFields = true;
                    csvWriter.Configuration.RegisterClassMap(new CSV.MatchRecordConfiguration());

                    csvWriter.WriteHeader <MatchRecord>();
                    csvWriter.NextRecord();
                }
            }
        }
Exemple #18
0
        private void WriteScheduledBookings(string scheduleId, DateTime scheduledTimeUTC, IEnumerable <string> bookingIds)
        {
            var unschBookings = LoadUnscheduledBookings();

            foreach (var bookingId in bookingIds)
            {
                using (var f = File.Open(Path.Combine(CSVBasePath, Path.Combine(ScheduledBookingsPath, bookingId + ".csv")), FileMode.Create))
                    using (var stream = new StreamWriter(f))
                        using (var csv = new CsvHelper.CsvWriter(stream, CultureInfo.InvariantCulture))
                        {
                            csv.Configuration.TypeConverterOptionsCache.GetOptions <DateTime>().Formats
                                = new string[] { "yyyy-MM-ddTHH:mm:ssZ" };
                            csv.WriteHeader <ScheduledBookingCsvRow>();
                            csv.NextRecord();

                            if (unschBookings.ContainsKey(bookingId))
                            {
                                foreach (var p in unschBookings[bookingId].Parts)
                                {
                                    csv.WriteRecord(new ScheduledBookingCsvRow
                                    {
                                        ScheduledTimeUTC = scheduledTimeUTC,
                                        Part             = p.Part,
                                        Quantity         = p.Quantity,
                                        ScheduleId       = scheduleId
                                    });
                                    csv.NextRecord();
                                }
                            }
                            else
                            {
                                csv.WriteRecord(new ScheduledBookingCsvRow
                                {
                                    ScheduledTimeUTC = scheduledTimeUTC,
                                    Part             = "",
                                    Quantity         = 0,
                                    ScheduleId       = scheduleId
                                });
                                csv.NextRecord();
                            }

                            stream.Flush();
                            //f.Flush(true);
                            f.Flush();
                        }
            }
        }
Exemple #19
0
        public void WriteCSVFile(string fileName, List <IInstruction> fileContents, StringCollection fileStrings)
        {
            fileName = Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName) + ".csv");

            DirectoryGuard.CheckDirectory(fileName);
            FileStream   fs = new FileStream(fileName, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);

            var csv = new CsvHelper.CsvWriter(sw);

            csv.Configuration.RegisterClassMap <CSVRecordMap>();

            csv.WriteHeader <CSVRecord>();
            csv.NextRecord();

            string lastSpeaker = "";

            foreach (var instruction in fileContents)
            {
                if (instruction is IHasStrings)
                {
                    var temp = instruction as IHasStrings;
                    List <CSVRecord> csvRecords = temp.GetCSVRecords();
                    foreach (var record in csvRecords)
                    {
                        record.originalText = fileStrings.GetString(record.stringID);
                        if (record.speaker != lastSpeaker)
                        {
                            lastSpeaker = record.speaker;
                        }
                        else
                        {
                            record.speaker = ""; // blank out the name of the speaker if it is being repeated to make it easier to note when speaker changes and avoid massive walls of speakers text
                        }
                        csv.WriteRecord(record);
                        csv.NextRecord();
                    }
                }
            }

            csv.Flush();

            sw.Close();
            fs.Close();
        }
        public HttpResponseMessage DownloadCsv(GenerateCsvModel model)
        {
            // Variables.
            var start = model.StartDate.HasValue
                ? model.StartDate.Value
                : SqlDateTime.MinValue.Value;
            var stop = model.EndDate.HasValue
                ? model.EndDate.Value.AddDays(1)
                : SqlDateTime.MaxValue.Value;

            // Get history items.
            var items = HistoryHelper.GetHistoryItems(start, stop);

            var config = new CsvHelper.Configuration.CsvConfiguration()
            {
                HasHeaderRecord = true,
                QuoteAllFields  = true
            };


            // write CSV data to memory stream
            using (var stream = new MemoryStream()) {
                using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true)) {
                    using (var csvWriter = new CsvHelper.CsvWriter(writer, config)) {
                        csvWriter.WriteHeader <HistoryCsvHeader>();
                        foreach (var item in items)
                        {
                            csvWriter.WriteField(item.Timestamp.ToString());
                            csvWriter.WriteField(item.Message);
                            csvWriter.NextRecord();
                        }
                    }
                }

                stream.Seek(0, SeekOrigin.Begin);

                return(CreateFileResponse(
                           stream.ToArray(),
                           $"site-activity_{start.ToString("yyyy-MM-dd")}_{stop.ToString("yyyy-MM-dd")}.csv",
                           "text/csv"
                           ));
            }
        }
        } // end sub

        /// <summary>
        /// <para xml:lang="en">Dump properties of a object to a TSV file. Output multiple objects on each rows of the TSV file.</para>
        /// <para xml:lang="ja">オブジェクトのプロパティをTSVファイルにダンプします。複数のオブジェクトをTSVファイルの各行に出力します。</para>
        /// </summary>
        /// <typeparam name="T">
        /// <para xml:lang="en">The type of object to dump.</para>
        /// <para xml:lang="ja">ダンプするオブジェクトの型</para>
        /// </typeparam>
        /// <param name="target">
        /// <para xml:lang="en">The collection of objects to dump.</para>
        /// <para xml:lang="ja">ダンプするオブジェクトのコレクション</para>
        /// </param>
        /// <param name="name">
        /// <para xml:lang="en">The name which is used for a file.</para>
        /// <para xml:lang="ja">ファイルに使用される名前。</para>
        /// </param>
        /// <param name="format">
        /// <para xml:lang="en">
        /// The lambda expression which is used for choosing properties to dump.
        /// Set like <code>a=&gt;new {a.A, a.B}</code>  to dump A property and B property of the object.
        /// Set like <code>a=&gt;a</code>  to dump all properties of the object.
        /// </para>
        /// <para xml:lang="ja">
        /// ダンプするプロパティを選択するラムダ式。
        /// オブジェクトのAプロパティとBプロパティをダンプする場合には、<code>a=&gt;new {a.A, a.B}</code> のように指定します。
        /// 全てのプロパティをダンプする場合には<code>a=&gt;a</code>を指定します。
        /// </para>
        /// </param>
        /// <param name="writeHeader">
        /// <para xml:lang="en">
        /// Set true to output a header of a TSV file. The names of properties of the object are output.
        /// Set false and so a header is not outputted. Use the DumpTsvHeader method or the WriteTsvHeader method to output the header, separately.
        /// </para>
        /// <para xml:lang="ja">
        /// TSVファイルの1行目にヘッダを出力する場合はtrueを指定します。オブジェクトのプロパティ名が出力されます。
        /// falseを指定するとヘッダが出力されません。別途、DumpTsvHeaderメソッドやWriteTsvHeaderメソッドを使用してヘッダを出力してください。
        /// </para>
        /// </param>
        public static void DumpTsv <T>(IEnumerable <T> target, string name, Func <T, object> format, bool writeHeader = true)
        {
            Dumper.WriteTextFile(name, ".tsv", writer =>
            {
                var configuration = new CsvHelper.Configuration.Configuration {
                    Delimiter = "\t"
                };
                using (var tsv = new CsvHelper.CsvWriter(writer, configuration))
                {
                    var isFirst = true;
                    foreach (var item in target)
                    {
                        var v = format(item);
                        if (isFirst)
                        {
                            isFirst = false;
                            if (writeHeader)
                            {
                                if (typeof(T) == typeof(string))
                                {
                                    tsv.WriteField("string");
                                }
                                else
                                {
                                    tsv.WriteHeader(v.GetType());
                                } // end if
                                tsv.NextRecord();
                            }
                        } // end if

                        if (typeof(T) == typeof(string))
                        {
                            tsv.WriteField(v);
                        }
                        else
                        {
                            tsv.WriteRecord(v);
                        } // end if
                        tsv.NextRecord();
                    }     // next item
                }         // end using (tsv)
            });
        }                 // end sub
Exemple #22
0
        static void Main(string[] args)
        {
            List <Musteri> musterilerim = new List <Musteri>();

            for (int i = 0; i < 50; i++)
            {
                Musteri m1 = new Musteri();
                m1.ID              = Guid.NewGuid();
                m1.Isim            = FakeData.NameData.GetFirstName();
                m1.Soyisim         = FakeData.NameData.GetSurname();
                m1.Telefonnumarasi = FakeData.PhoneNumberData.GetPhoneNumber();
                m1.Emailadres      = $"{m1.Isim}.{m1.Soyisim}@{FakeData.NetworkData.GetDomain()}";
                musterilerim.Add(m1);
            }

            if (Directory.Exists("C:\\CSV\\"))
            {
            }
            else
            {
                Directory.CreateDirectory("C:\\CSV\\");
            }

            StreamReader SR = new StreamReader("C:\\CSV\\Musteriler.csv");

            CsvHelper.CsvReader reader     = new CsvHelper.CsvReader(SR);
            List <Musteri>      okunandata = reader.GetRecords <Musteri>().ToList();


            StreamWriter SW = new StreamWriter("C:\\CSV\\Musteriler.csv");

            CsvHelper.CsvWriter write = new CsvHelper.CsvWriter(SW);
            write.WriteHeader(typeof(Musteri));
            foreach (Musteri item in musterilerim)
            {
                write.WriteRecord(item);
            }
            SW.Close();

            Console.WriteLine("CSV olarak kayit islemi tamamlanmistir.");
            Console.WriteLine($"Toplam Adet: {musterilerim.Count}");
            Console.ReadKey();
        }
Exemple #23
0
        public async Task ConvertCsv()
        {
            var csvPath = @"C:\Users\sweet\Downloads\Beat Buddy Midi Drum Map - Map (1).csv";

            using (var reader = new StreamReader(csvPath))
                using (var writer = new StreamWriter("map.csv"))
                    using (var csvReader = new CsvHelper.CsvReader(reader, CultureInfo.InvariantCulture))
                        using (var csvWriter = new CsvHelper.CsvWriter(writer, new CsvConfiguration(CultureInfo.InvariantCulture)))
                        {
                            await csvReader.ReadAsync();

                            csvReader.ReadHeader();
                            csvWriter.WriteHeader <Record>();
                            await csvWriter.NextRecordAsync();

                            while (await csvReader.ReadAsync())
                            {
                                var inRecord  = csvReader.GetRecord <dynamic>() as IDictionary <string, object>;
                                var keys      = inRecord.Keys;
                                var outRecord = new Record()
                                {
                                    Number         = Convert.ToInt32(inRecord["Number"]),
                                    MidiNote       = Convert.ToString(inRecord["Note"]),
                                    OctaveMiddleC3 = Convert.ToInt32(inRecord["Octave (Middle C3)"]),
                                    OctaveMiddleC4 = Convert.ToInt32(inRecord["Octave (Middle C4)"])
                                };
                                for (var k = 4; k < keys.Count; k++)
                                {
                                    var key   = keys.ElementAt(k);
                                    var value = Convert.ToString(inRecord[key]);
                                    // if (string.IsNullOrWhiteSpace(value))
                                    //    continue;
                                    var instrimentNote = GetInstrumentNote(value);
                                    outRecord.Kit        = key;
                                    outRecord.Instrument = instrimentNote.Instrument;
                                    outRecord.KitNote    = instrimentNote.KitNote;
                                    csvWriter.WriteRecord(outRecord);
                                    await csvWriter.NextRecordAsync();
                                }
                            }
                        }
        }
Exemple #24
0
        private static void CSVOluşturma()
        {
            List <Kullanici> Kullanicilar = new List <Kullanici>();

            Kullanici k1 = new Kullanici();

            k1.ID      = Guid.NewGuid();
            k1.Isim    = "Salih";
            k1.Soyisim = "SEKER";
            k1.Numara  = 1;
            k1.Github  = "github.com/salihseker";

            Kullanicilar.Add(k1);

            Kullanici k2 = new Kullanici();

            k2.ID      = Guid.NewGuid();
            k2.Isim    = "Kerami";
            k2.Soyisim = "Ozsoy";
            k2.Numara  = 2;
            k2.Github  = "github.com/keramiozsoy";

            Kullanicilar.Add(k2);

            for (int i = 0; i < 10; i++)
            {
                Kullanicilar.Add(k1);
                Kullanicilar.Add(k2);
            }

            // Yazma işlemi.
            StreamWriter SW = new StreamWriter(@"D:\Kullanicilar.csv");

            CsvHelper.CsvWriter Write = new CsvHelper.CsvWriter(SW);
            Write.WriteHeader(typeof(Kullanici));
            foreach (Kullanici item in Kullanicilar)
            {
                Write.WriteRecord(item);
            }
            SW.Close();
        }
Exemple #25
0
        private static void ReMakeRecords(int playerCount)
        {
            var csvFilePath = Path.Combine(Directory.GetCurrentDirectory(), $"all-in-versusFold-{playerCount}players.csv");

            Console.WriteLine(csvFilePath);

            using (var fileStream = new FileStream(csvFilePath, FileMode.Create))
            {
                using (var writer = new StreamWriter(fileStream, Encoding.UTF8))
                {
                    using (var csvWriter = new CsvHelper.CsvWriter(writer))
                    {
                        csvWriter.WriteHeader <AllInSimulation.SimulationResult>();
                        csvWriter.Flush();
                        writer.WriteLine();
                        writer.Flush();

                        var simulation        = new AllInVersusFoldBadCardsSimulation();
                        var simulationResults = simulation.Run(new AllInSimulation.SimulationOptions
                        {
                            ConfidenceLevel = ConfidenceLevel.L95,
                            WinLoseRatesDesiredRelativeError = 0.02,
                            BalanceDesiredAbsoluteError      = 0.01,
                            PlayerCount = playerCount
                        });

                        var watch = Stopwatch.StartNew();
                        foreach (var result in simulationResults)
                        {
                            csvWriter.WriteRecord(result);
                            csvWriter.Flush();
                            writer.WriteLine();
                            writer.Flush();

                            Console.WriteLine($"Processed {result.Card1}, {result.Card2}. Elapsed totally {watch.Elapsed}, Time: {DateTime.Now}");
                        }
                    }
                }
            }
        }
        protected override void OutBlock(ResModel resModel, IXAQuery query, CsvHelper.CsvWriter writer)
        {
            var szTrCode = resModel.Name;
            var block    = resModel.Blocks[szTrCode + "OutBlock"];

            writer.WriteHeader <_t8425OutBlock>();
            for (var i = 0; i < query.GetBlockCount(block.Name); i++)
            {
                var result = new _t8425OutBlock()
                {
                    tmcode = query.GetFieldData(block.Name, "tmcode", i),
                    tmname = query.GetFieldData(block.Name, "tmname", i),
                };
                writer.NextRecord();
                writer.WriteRecord(result);
                Constants.CodeThemes.Add(result.tmcode, new CodeTheme()
                {
                    Code = result.tmcode,
                    Name = result.tmname,
                });
            }
        }
Exemple #27
0
        protected override void OutBlock(ResModel resModel, IXAQuery query, CsvHelper.CsvWriter writer)
        {
            var szTrCode = resModel.Name;
            var block    = resModel.Blocks[szTrCode + "OutBlock"];

            writer.WriteHeader <_t8436OutBlock>();
            for (var i = 0; i < query.GetBlockCount(block.Name); i++)
            {
                var result = new _t8436OutBlock()
                {
                    hname      = query.GetFieldData(block.Name, "hname", i),
                    shcode     = query.GetFieldData(block.Name, "shcode", i),
                    expcode    = query.GetFieldData(block.Name, "expcode", i),
                    etfgubun   = query.GetFieldData(block.Name, "etfgubun", i),
                    uplmtprice = long.Parse(query.GetFieldData(block.Name, "uplmtprice", i)),
                    dnlmtprice = long.Parse(query.GetFieldData(block.Name, "dnlmtprice", i)),
                    jnilclose  = long.Parse(query.GetFieldData(block.Name, "jnilclose", i)),
                    memedan    = query.GetFieldData(block.Name, "memedan", i),
                    recprice   = long.Parse(query.GetFieldData(block.Name, "recprice", i)),
                    gubun      = query.GetFieldData(block.Name, "gubun", i),
                    bu12gubun  = query.GetFieldData(block.Name, "bu12gubun", i),
                    spac_gubun = query.GetFieldData(block.Name, "spac_gubun", i),
                    filler     = query.GetFieldData(block.Name, "filler", i),
                };
                writer.NextRecord();
                writer.WriteRecord(result);
                Constants.CodeStocks.Add(result.shcode, new CodeStock()
                {
                    Name         = result.hname,
                    Code         = result.shcode,
                    ExpandedCode = result.expcode,
                    EtfGubun     = result.etfgubun,
                    SpacGubun    = result.spac_gubun,
                    MarketGubun  = result.gubun,
                    Bu12Gubun    = result.bu12gubun,
                });
            }
        }
        public int CSVDataVer()
        {
            int Sonuc = 0;

            try
            {
                List <RehberKayit>  Kayitlar = DLL.RehberKayitlariGetir();
                StreamWriter        SW       = new StreamWriter(@"c:\TelefonRehberiDB\DataVerCSV.csv");
                CsvHelper.CsvWriter Write    = new CsvHelper.CsvWriter(SW);
                Write.WriteHeader(typeof(RehberKayit));
                foreach (var item in Kayitlar)
                {
                    Write.WriteRecord(item);
                }
                SW.Close();
                Sonuc = 1;
            }
            catch (Exception ex)
            {
                Sonuc = 0;
            }
            return(Sonuc);
        }
        public int CsvDataVer()
        {
            int Sonuc = 0;

            try
            {
                List <RehberKayit>  Kayitlarim = DLL.RehberKayitlariGetir();
                StreamWriter        SW         = new StreamWriter(@"c:\TelefonRehberiDB\DataVerCSV.csv");
                CsvConfiguration    config     = new CsvConfiguration(new CultureInfo("TR"));
                CsvHelper.CsvWriter Write      = new CsvHelper.CsvWriter(SW, config);
                Write.WriteHeader(typeof(RehberKayit));

                Write.WriteRecords(Kayitlarim);

                SW.Close();
                Sonuc = 1;
            }
            catch (Exception)
            {
                throw;
            }
            return(Sonuc);
        }
Exemple #30
0
        public bool writetofile(string query)
        {
            using (var textwriter = new StreamWriter(query))

            {
                try
                {
                    if (winners.Count > 0)
                    {
                        var writer = new CsvHelper.CsvWriter(textwriter, false);
                        writer.Configuration.Delimiter = ",";

                        writer.WriteComment("This draw name is " + drawname + " ." + "Draw Dated on " + DateTime.Now.ToString());
                        writer.NextRecord();
                        writer.WriteHeader <KeyValuePair <int, string> >();
                        writer.NextRecord();

                        foreach (var item in winners)
                        {
                            writer.WriteField(item.Key);
                            writer.WriteField(item.Value);
                            writer.NextRecord();
                        }

                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Exemple #31
0
        private static void Main(string[] args)
        {
            Licensing.RegisterLicenseFromFileIfExists(SSLicenseFile);

            SetupNLog();

            _keywords = new HashSet<string> {"temp", "tmp"};

            _logger = LogManager.GetCurrentClassLogger();

            if (!CheckForDotnet46())
            {
                _logger.Warn(".net 4.6 not detected. Please install .net 4.6 and try again.");
                return;
            }

            _fluentCommandLineParser = new FluentCommandLineParser<ApplicationArguments>
            {
                IsCaseSensitive = false
            };

            _fluentCommandLineParser.Setup(arg => arg.File)
                .As('f')
                .WithDescription("File to process. Either this or -d is required");

            _fluentCommandLineParser.Setup(arg => arg.Directory)
                .As('d')
                .WithDescription("Directory to recursively process. Either this or -f is required");

            _fluentCommandLineParser.Setup(arg => arg.Keywords)
                .As('k')
                .WithDescription(
                    "Comma separated list of keywords to highlight in output. By default, 'temp' and 'tmp' are highlighted. Any additional keywords will be added to these.");

            _fluentCommandLineParser.Setup(arg => arg.Quiet)
                .As('q')
                .WithDescription(
                    "Do not dump full details about each file processed. Speeds up processing when using --json or --csv\r\n")
                .SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.JsonDirectory)
                .As("json")
                .WithDescription(
                    "Directory to save json representation to. Use --pretty for a more human readable layout");

            _fluentCommandLineParser.Setup(arg => arg.CsvDirectory)
                .As("csv")
                .WithDescription(
                    "Directory to save CSV (tab separated) results to. Be sure to include the full path in double quotes");

//            _fluentCommandLineParser.Setup(arg => arg.XmlDirectory)
//               .As("xml")
//               .WithDescription(
//                   "Directory to save XML formatted results to. Be sure to include the full path in double quotes");

            _fluentCommandLineParser.Setup(arg => arg.xHtmlDirectory)
                .As("html")
                .WithDescription(
                    "Directory to save xhtml formatted results to. Be sure to include the full path in double quotes");

            _fluentCommandLineParser.Setup(arg => arg.JsonPretty)
                .As("pretty")
                .WithDescription(
                    "When exporting to json, use a more human readable layout\r\n").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.LocalTime)
                .As("local")
                .WithDescription(
                    "Display dates using timezone of machine PECmd is running on vs. UTC\r\n").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.DateTimeFormat)
.As("dt")
.WithDescription(
  "The custom date/time format to use when displaying time stamps. Default is: yyyy-MM-dd HH:mm:ss K").SetDefault("yyyy-MM-dd HH:mm:ss K");

            _fluentCommandLineParser.Setup(arg => arg.PreciseTimestamps)
   .As("mp")
   .WithDescription(
       "When true, display higher precision for time stamps. Default is false").SetDefault(false);


            var header =
                $"PECmd version {Assembly.GetExecutingAssembly().GetName().Version}" +
                "\r\n\r\nAuthor: Eric Zimmerman ([email protected])" +
                "\r\nhttps://github.com/EricZimmerman/PECmd";

            var footer = @"Examples: PECmd.exe -f ""C:\Temp\CALC.EXE-3FBEF7FD.pf""" + "\r\n\t " +
                         @" PECmd.exe -f ""C:\Temp\CALC.EXE-3FBEF7FD.pf"" --json ""D:\jsonOutput"" --jsonpretty" +
                         "\r\n\t " +
                         @" PECmd.exe -d ""C:\Temp"" -k ""system32, fonts""" + "\r\n\t " +
                         @" PECmd.exe -d ""C:\Temp"" --csv ""c:\temp"" --local --json c:\temp\json" +
                         "\r\n\t " +
//                         @" PECmd.exe -f ""C:\Temp\someOtherFile.txt"" --lr cc -sa" + "\r\n\t " +
//                         @" PECmd.exe -f ""C:\Temp\someOtherFile.txt"" --lr cc -sa -m 15 -x 22" + "\r\n\t " +
                         @" PECmd.exe -d ""C:\Windows\Prefetch""" + "\r\n\t " +
                         "\r\n\t" +
                         "  Short options (single letter) are prefixed with a single dash. Long commands are prefixed with two dashes\r\n";

            _fluentCommandLineParser.SetupHelp("?", "help")
                .WithHeader(header)
                .Callback(text => _logger.Info(text + "\r\n" + footer));

            var result = _fluentCommandLineParser.Parse(args);

            if (result.HelpCalled)
            {
                return;
            }

            if (result.HasErrors)
            {
                _logger.Error("");
                _logger.Error(result.ErrorText);

                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.File) &&
                UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.Directory))
            {
                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                _logger.Warn("Either -f or -d is required. Exiting");
                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.File) == false &&
                !File.Exists(_fluentCommandLineParser.Object.File))
            {
                _logger.Warn($"File '{_fluentCommandLineParser.Object.File}' not found. Exiting");
                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.Directory) == false &&
                !Directory.Exists(_fluentCommandLineParser.Object.Directory))
            {
                _logger.Warn($"Directory '{_fluentCommandLineParser.Object.Directory}' not found. Exiting");
                return;
            }

            if (_fluentCommandLineParser.Object.Keywords?.Length > 0)
            {
                var kws = _fluentCommandLineParser.Object.Keywords.Split(new[] {','},
                    StringSplitOptions.RemoveEmptyEntries);

                foreach (var kw in kws)
                {
                    _keywords.Add(kw.Trim());
                }
            }



            _logger.Info(header);
            _logger.Info("");
            _logger.Info($"Command line: {string.Join(" ", Environment.GetCommandLineArgs().Skip(1))}");
            _logger.Info("");
            _logger.Info($"Keywords: {string.Join(", ", _keywords)}");
            _logger.Info("");

            if (_fluentCommandLineParser.Object.PreciseTimestamps)
            {
                _fluentCommandLineParser.Object.DateTimeFormat = _preciseTimeFormat;
            }

            _processedFiles = new List<IPrefetch>();

            _failedFiles = new List<string>();

            if (_fluentCommandLineParser.Object.File?.Length > 0)
            {
                IPrefetch pf = null;

                try
                {
                    pf = LoadFile(_fluentCommandLineParser.Object.File);
                    if (pf != null)
                    {
                        _processedFiles.Add(pf);
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    _logger.Error(
                        $"Unable to access '{_fluentCommandLineParser.Object.File}'. Are you running as an administrator? Error: {ex.Message}");
                }
                catch (Exception ex)
                {
                    _logger.Error(
                        $"Error getting prefetch files in '{_fluentCommandLineParser.Object.Directory}'. Error: {ex.Message}");
                }
            }
            else
            {
                _logger.Info($"Looking for prefetch files in '{_fluentCommandLineParser.Object.Directory}'");
                _logger.Info("");

                string[] pfFiles = null;

              

                try
                {
                    pfFiles = Directory.GetFiles(_fluentCommandLineParser.Object.Directory, "*.pf",
                        SearchOption.AllDirectories);
                }
                catch (UnauthorizedAccessException ua)
                {
                    _logger.Error(
                        $"Unable to access '{_fluentCommandLineParser.Object.Directory}'. Are you running as an administrator? Error: {ua.Message}");
                    return;
                }
                catch (Exception ex)
                {
                    _logger.Error(
                        $"Error getting prefetch files in '{_fluentCommandLineParser.Object.Directory}'. Error: {ex.Message}");
                    return;
                }

                _logger.Info($"Found {pfFiles.Length:N0} Prefetch files");
                _logger.Info("");

                var sw = new Stopwatch();
                sw.Start();

                foreach (var file in pfFiles)
                {
                    var pf = LoadFile(file);
                    if (pf != null)
                    {
                        _processedFiles.Add(pf);
                    }
                }

                sw.Stop();

                if (_fluentCommandLineParser.Object.Quiet)
                {
                    _logger.Info("");
                }

                _logger.Info(
                    $"Processed {pfFiles.Length - _failedFiles.Count:N0} out of {pfFiles.Length:N0} files in {sw.Elapsed.TotalSeconds:N4} seconds");

                if (_failedFiles.Count > 0)
                {
                    _logger.Info("");
                    _logger.Warn("Failed files");
                    foreach (var failedFile in _failedFiles)
                    {
                        _logger.Info($"  {failedFile}");
                    }
                }

            }

            if (_processedFiles.Count > 0)
            {
                _logger.Info("");

                try
                {
                    CsvWriter csv = null;
                    StreamWriter streamWriter = null;

                    CsvWriter csvTl = null;
                    StreamWriter streamWriterTl = null;


                    if (_fluentCommandLineParser.Object.CsvDirectory?.Length > 0)
                    {
                        var outName = $"{DateTimeOffset.Now.ToString("yyyyMMddHHmmss")}_PECmd_Output.tsv";
                        var outNameTl = $"{DateTimeOffset.Now.ToString("yyyyMMddHHmmss")}_PECmd_Output_Timeline.tsv";
                        var outFile = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);
                        var outFileTl = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outNameTl);


                        if (Directory.Exists(_fluentCommandLineParser.Object.CsvDirectory) == false)
                        {
                            _logger.Warn($"Path to '{_fluentCommandLineParser.Object.CsvDirectory}' doesn't exist. Creating...");
                            Directory.CreateDirectory(_fluentCommandLineParser.Object.CsvDirectory);
                        }

                        _logger.Warn($"CSV (tab separated) output will be saved to '{outFile}'");
                        _logger.Warn($"CSV time line (tab separated) output will be saved to '{outFileTl}'");

                        try
                        {
                            streamWriter = new StreamWriter(outFile);
                            csv = new CsvWriter(streamWriter);
                            csv.Configuration.Delimiter = $"{'\t'}";
                            csv.WriteHeader(typeof(CsvOut));

                            streamWriterTl = new StreamWriter(outFileTl);
                            csvTl = new CsvWriter(streamWriterTl);
                            csvTl.Configuration.Delimiter = $"{'\t'}";
                            csvTl.WriteHeader(typeof(CsvOutTl));
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(
                                $"Unable to open '{outFile}' for writing. CSV export canceled. Error: {ex.Message}");
                        }
                    }

                    if (_fluentCommandLineParser.Object.JsonDirectory?.Length > 0)
                    {
                        _logger.Warn($"Saving json output to '{_fluentCommandLineParser.Object.JsonDirectory}'");
                    }

                    XmlTextWriter xml = null;

                    if (_fluentCommandLineParser.Object.xHtmlDirectory?.Length > 0)
                    {
                        var outDir = Path.Combine(_fluentCommandLineParser.Object.xHtmlDirectory,
                            $"{DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmss")}_PECmd_Output_for_{_fluentCommandLineParser.Object.xHtmlDirectory.Replace(@":\", "_").Replace(@"\", "_")}");

                        if (Directory.Exists(outDir) == false)
                        {
                            Directory.CreateDirectory(outDir);
                        }

                        var styleDir = Path.Combine(outDir, "styles");
                        if (Directory.Exists(styleDir) == false)
                        {
                            Directory.CreateDirectory(styleDir);
                        }

                        File.WriteAllText(Path.Combine(styleDir, "normalize.css"), Resources.normalize);
                        File.WriteAllText(Path.Combine(styleDir, "style.css"), Resources.style);

                        Resources.directories.Save(Path.Combine(styleDir, "directories.png"));
                        Resources.filesloaded.Save(Path.Combine(styleDir, "filesloaded.png"));

                        var outFile = Path.Combine(_fluentCommandLineParser.Object.xHtmlDirectory, outDir,
                            "index.xhtml");

                        _logger.Warn($"Saving HTML output to '{outFile}'");

                        xml = new XmlTextWriter(outFile, Encoding.UTF8)
                        {
                            Formatting = Formatting.Indented,
                            Indentation = 4
                        };

                        xml.WriteStartDocument();

                        xml.WriteProcessingInstruction("xml-stylesheet", "href=\"styles/normalize.css\"");
                        xml.WriteProcessingInstruction("xml-stylesheet", "href=\"styles/style.css\"");

                        xml.WriteStartElement("document");
                    }

                    foreach (var processedFile in _processedFiles)
                    {
                        var o = GetCsvFormat(processedFile);

                        try
                        {
                            foreach (var dateTimeOffset in processedFile.LastRunTimes)
                            {
                                var t = new CsvOutTl();

                                var exePath =
                                    processedFile.Filenames.FirstOrDefault(
                                        y => y.EndsWith(processedFile.Header.ExecutableFilename));

                                if (exePath == null)
                                {
                                    exePath = processedFile.Header.ExecutableFilename;
                                }

                                t.ExecutableName = exePath;
                                t.RunTime = dateTimeOffset.ToString(_fluentCommandLineParser.Object.DateTimeFormat);

                                csvTl?.WriteRecord(t);
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(
                                $"Error getting time line record for '{processedFile.SourceFilename}' to '{_fluentCommandLineParser.Object.CsvDirectory}'. Error: {ex.Message}");

                        }

                        try
                        {
                            csv?.WriteRecord(o);
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(
                                $"Error writing CSV record for '{processedFile.SourceFilename}' to '{_fluentCommandLineParser.Object.CsvDirectory}'. Error: {ex.Message}");
                        }

                        if (_fluentCommandLineParser.Object.JsonDirectory?.Length > 0)
                        {
                            SaveJson(processedFile, _fluentCommandLineParser.Object.JsonPretty,
                                _fluentCommandLineParser.Object.JsonDirectory);
                        }

                        //XHTML
                        xml?.WriteStartElement("Container");
                        xml?.WriteElementString("SourceFile", o.SourceFilename);
                        xml?.WriteElementString("SourceCreated", o.SourceCreated);
                        xml?.WriteElementString("SourceModified", o.SourceModified);
                        xml?.WriteElementString("SourceAccessed", o.SourceAccessed);

                        xml?.WriteElementString("LastRun", o.LastRun);

                        xml?.WriteElementString("PreviousRun0", $"{o.PreviousRun0}");
                        xml?.WriteElementString("PreviousRun1", $"{o.PreviousRun1}");
                        xml?.WriteElementString("PreviousRun2", $"{o.PreviousRun2}");
                        xml?.WriteElementString("PreviousRun3", $"{o.PreviousRun3}");
                        xml?.WriteElementString("PreviousRun4", $"{o.PreviousRun4}");
                        xml?.WriteElementString("PreviousRun5", $"{o.PreviousRun5}");
                        xml?.WriteElementString("PreviousRun6", $"{o.PreviousRun6}");

                        xml?.WriteStartElement("ExecutableName");
                        xml?.WriteAttributeString("title", "Note: The name of the executable tracked by the pf file");
                        xml?.WriteString(o.ExecutableName);
                        xml?.WriteEndElement();

                        xml?.WriteElementString("RunCount", $"{o.RunCount}");

                        xml?.WriteStartElement("Size");
                        xml?.WriteAttributeString("title", "Note: The size of the executable in bytes");
                        xml?.WriteString(o.Size);
                        xml?.WriteEndElement();

                        xml?.WriteStartElement("Hash");
                        xml?.WriteAttributeString("title", "Note: The calculated hash for the pf file that should match the hash in the source file name");
                        xml?.WriteString(o.Hash);
                        xml?.WriteEndElement();

                        xml?.WriteStartElement("Version");
                        xml?.WriteAttributeString("title", "Note: The operating system that generated the prefetch file");
                        xml?.WriteString(o.Version);
                        xml?.WriteEndElement();

                        xml?.WriteElementString("Note", o.Note);

                        xml?.WriteElementString("Volume0Name", o.Volume0Name);
                        xml?.WriteElementString("Volume0Serial", o.Volume0Serial);
                        xml?.WriteElementString("Volume0Created", o.Volume0Created);

                        xml?.WriteElementString("Volume1Name", o.Volume1Name);
                        xml?.WriteElementString("Volume1Serial", o.Volume1Serial);
                        xml?.WriteElementString("Volume1Created", o.Volume1Created);


                        xml?.WriteStartElement("Directories");
                        xml?.WriteAttributeString("title", "A comma separated list of all directories accessed by the executable");
                        xml?.WriteString(o.Directories);
                        xml?.WriteEndElement();

                        xml?.WriteStartElement("FilesLoaded");
                        xml?.WriteAttributeString("title", "A comma separated list of all files that were loaded by the executable");
                        xml?.WriteString(o.FilesLoaded);
                        xml?.WriteEndElement();

                        xml?.WriteEndElement();

                    }


                    //Close CSV stuff
                    streamWriter?.Flush();
                    streamWriter?.Close();

                    streamWriterTl?.Flush();
                    streamWriterTl?.Close();

                    //Close XML
                    xml?.WriteEndElement();
                    xml?.WriteEndDocument();
                    xml?.Flush();
                }
                catch (Exception ex)
                {
                    _logger.Error($"Error exporting data! Error: {ex.Message}");
                }
            }
        }
Exemple #32
-1
        private static void Main(string[] args)
        {
            Licensing.RegisterLicenseFromFileIfExists(SSLicenseFile);

            LoadMACs();

            SetupNLog();

            _logger = LogManager.GetCurrentClassLogger();

            if (!CheckForDotnet46())
            {
                _logger.Warn(".net 4.6 not detected. Please install .net 4.6 and try again.");
                return;
            }

            _fluentCommandLineParser = new FluentCommandLineParser<ApplicationArguments>
            {
                IsCaseSensitive = false
            };

            _fluentCommandLineParser.Setup(arg => arg.File)
                .As('f')
                .WithDescription("File to process. Either this or -d is required");

            _fluentCommandLineParser.Setup(arg => arg.Directory)
                .As('d')
                .WithDescription("Directory to recursively process. Either this or -f is required");

            _fluentCommandLineParser.Setup(arg => arg.AllFiles)
                .As("all")
                .WithDescription(
                    "Process all files in directory vs. only files matching *.lnk\r\n").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.CsvDirectory)
                .As("csv")
                .WithDescription(
                    "Directory to save CSV (tab separated) formatted results to. Be sure to include the full path in double quotes");

            _fluentCommandLineParser.Setup(arg => arg.XmlDirectory)
                .As("xml")
                .WithDescription(
                    "Directory to save XML formatted results to. Be sure to include the full path in double quotes");

            _fluentCommandLineParser.Setup(arg => arg.xHtmlDirectory)
                .As("html")
                .WithDescription(
                    "Directory to save xhtml formatted results to. Be sure to include the full path in double quotes");

            _fluentCommandLineParser.Setup(arg => arg.JsonDirectory)
                .As("json")
                .WithDescription(
                    "Directory to save json representation to. Use --pretty for a more human readable layout");

            _fluentCommandLineParser.Setup(arg => arg.JsonPretty)
                .As("pretty")
                .WithDescription(
                    "When exporting to json, use a more human readable layout\r\n").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.Quiet)
                .As('q')
                .WithDescription(
                    "Only show the filename being processed vs all output. Useful to speed up exporting to json and/or csv\r\n")
                .SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.NoTargetIDList)
                .As("nid")
                .WithDescription(
                    "Suppress Target ID list details from being displayed. Default is false.").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.NoExtraBlocks)
                .As("neb")
                .WithDescription(
                    "Suppress Extra blocks information from being displayed. Default is false.\r\n").SetDefault(false);

            _fluentCommandLineParser.Setup(arg => arg.DateTimeFormat)
            .As("dt")
            .WithDescription(
            "The custom date/time format to use when displaying time stamps. Default is: yyyy-MM-dd HH:mm:ss K").SetDefault("yyyy-MM-dd HH:mm:ss K");

            _fluentCommandLineParser.Setup(arg => arg.PreciseTimestamps)
               .As("mp")
               .WithDescription(
               "Display higher precision for time stamps. Default is false").SetDefault(false);

            var header =
                $"LECmd version {Assembly.GetExecutingAssembly().GetName().Version}" +
                "\r\n\r\nAuthor: Eric Zimmerman ([email protected])" +
                "\r\nhttps://github.com/EricZimmerman/LECmd";

            var footer = @"Examples: LECmd.exe -f ""C:\Temp\foobar.lnk""" + "\r\n\t " +
                         @" LECmd.exe -f ""C:\Temp\somelink.lnk"" --json ""D:\jsonOutput"" --jsonpretty" + "\r\n\t " +
                         @" LECmd.exe -d ""C:\Temp"" --csv ""c:\temp"" --html c:\temp --xml c:\temp\xml -q" + "\r\n\t " +
                         @" LECmd.exe -f ""C:\Temp\some other link.lnk"" --nid --neb " + "\r\n\t " +
                         @" LECmd.exe -d ""C:\Temp"" --all" + "\r\n\t" +
                         "\r\n\t"+
                         "  Short options (single letter) are prefixed with a single dash. Long commands are prefixed with two dashes\r\n";

            _fluentCommandLineParser.SetupHelp("?", "help")
                .WithHeader(header)
                .Callback(text => _logger.Info(text + "\r\n" + footer));

            var result = _fluentCommandLineParser.Parse(args);

            if (result.HelpCalled)
            {
                return;
            }

            if (result.HasErrors)
            {
                _logger.Error("");
                _logger.Error(result.ErrorText);

                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.File) &&
                UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.Directory))
            {
                _fluentCommandLineParser.HelpOption.ShowHelp(_fluentCommandLineParser.Options);

                _logger.Warn("Either -f or -d is required. Exiting");
                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.File) == false &&
                !File.Exists(_fluentCommandLineParser.Object.File))
            {
                _logger.Warn($"File '{_fluentCommandLineParser.Object.File}' not found. Exiting");
                return;
            }

            if (UsefulExtension.IsNullOrEmpty(_fluentCommandLineParser.Object.Directory) == false &&
                !Directory.Exists(_fluentCommandLineParser.Object.Directory))
            {
                _logger.Warn($"Directory '{_fluentCommandLineParser.Object.Directory}' not found. Exiting");
                return;
            }

            _logger.Info(header);
            _logger.Info("");
            _logger.Info($"Command line: {string.Join(" ", Environment.GetCommandLineArgs().Skip(1))}\r\n");

            if (_fluentCommandLineParser.Object.PreciseTimestamps)
            {
                _fluentCommandLineParser.Object.DateTimeFormat = _preciseTimeFormat;
            }

            _processedFiles = new List<LnkFile>();

            _failedFiles = new List<string>();

            if (_fluentCommandLineParser.Object.File?.Length > 0)
            {
                LnkFile lnk = null;

                try
                {
                    lnk = ProcessFile(_fluentCommandLineParser.Object.File);
                    if (lnk != null)
                    {
                        _processedFiles.Add(lnk);
                    }
                }
                catch (UnauthorizedAccessException ua)
                {
                    _logger.Error(
                        $"Unable to access '{_fluentCommandLineParser.Object.File}'. Are you running as an administrator? Error: {ua.Message}");
                    return;
                }
                catch (Exception ex)
                {
                    _logger.Error(
                        $"Error processing file '{_fluentCommandLineParser.Object.Directory}' Please send it to [email protected]. Error: {ex.Message}");
                    return;
                }
            }
            else
            {
                _logger.Info($"Looking for lnk files in '{_fluentCommandLineParser.Object.Directory}'");
                _logger.Info("");

                string[] lnkFiles = null;

                try
                {
                    var mask = "*.lnk";
                    if (_fluentCommandLineParser.Object.AllFiles)
                    {
                        mask = "*";
                    }

                    lnkFiles = Directory.GetFiles(_fluentCommandLineParser.Object.Directory, mask,
                        SearchOption.AllDirectories);
                }
                catch (UnauthorizedAccessException ua)
                {
                    _logger.Error(
                        $"Unable to access '{_fluentCommandLineParser.Object.Directory}'. Error message: {ua.Message}");
                    return;
                }
                catch (Exception ex)
                {
                    _logger.Error(
                        $"Error getting lnk files in '{_fluentCommandLineParser.Object.Directory}'. Error: {ex.Message}");
                    return;
                }

                _logger.Info($"Found {lnkFiles.Length:N0} files");
                _logger.Info("");

                var sw = new Stopwatch();
                sw.Start();

                foreach (var file in lnkFiles)
                {
                    var lnk = ProcessFile(file);
                    if (lnk != null)
                    {
                        _processedFiles.Add(lnk);
                    }
                }

                sw.Stop();

                if (_fluentCommandLineParser.Object.Quiet)
                {
                    _logger.Info("");
                }

                _logger.Info(
                    $"Processed {lnkFiles.Length - _failedFiles.Count:N0} out of {lnkFiles.Length:N0} files in {sw.Elapsed.TotalSeconds:N4} seconds");
                if (_failedFiles.Count > 0)
                {
                    _logger.Info("");
                    _logger.Warn("Failed files");
                    foreach (var failedFile in _failedFiles)
                    {
                        _logger.Info($"  {failedFile}");
                    }
                }
            }

            if (_processedFiles.Count > 0)
            {
                _logger.Info("");

                try
                {
                    CsvWriter csv = null;
                    StreamWriter sw = null;

                    if (_fluentCommandLineParser.Object.CsvDirectory?.Length > 0)
                    {
                        if (Directory.Exists(_fluentCommandLineParser.Object.CsvDirectory) == false)
                        {
                            _logger.Warn($"'{_fluentCommandLineParser.Object.CsvDirectory} does not exist. Creating...'");
                            Directory.CreateDirectory(_fluentCommandLineParser.Object.CsvDirectory);
                        }

                        var outName = $"{DateTimeOffset.Now.ToString("yyyyMMddHHmmss")}_LECmd_Output.tsv";
                        var outFile = Path.Combine(_fluentCommandLineParser.Object.CsvDirectory, outName);

                        _fluentCommandLineParser.Object.CsvDirectory =
                            Path.GetFullPath(outFile);
                        _logger.Warn(
                            $"CSV (tab separated) output will be saved to '{Path.GetFullPath(outFile)}'");

                        try
                        {
                            sw = new StreamWriter(outFile);
                            csv = new CsvWriter(sw);
                            csv.Configuration.Delimiter = $"{'\t'}";
                            csv.WriteHeader(typeof(CsvOut));
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(
                                $"Unable to open '{outFile}' for writing. CSV export canceled. Error: {ex.Message}");
                        }
                    }

                    if (_fluentCommandLineParser.Object.JsonDirectory?.Length > 0)
                    {
                        if (Directory.Exists(_fluentCommandLineParser.Object.JsonDirectory) == false)
                        {
                            _logger.Warn($"'{_fluentCommandLineParser.Object.JsonDirectory} does not exist. Creating...'");
                            Directory.CreateDirectory(_fluentCommandLineParser.Object.JsonDirectory);
                        }
                        _logger.Warn($"Saving json output to '{_fluentCommandLineParser.Object.JsonDirectory}'");
                    }
                    if (_fluentCommandLineParser.Object.XmlDirectory?.Length > 0)
                    {
                        {
                            if (Directory.Exists(_fluentCommandLineParser.Object.XmlDirectory) == false)
                            {
                                _logger.Warn($"'{_fluentCommandLineParser.Object.XmlDirectory} does not exist. Creating...'");
                                Directory.CreateDirectory(_fluentCommandLineParser.Object.XmlDirectory);
                            }

                        }
                        _logger.Warn($"Saving XML output to '{_fluentCommandLineParser.Object.XmlDirectory}'");
                    }

                    XmlTextWriter xml = null;

                    if (_fluentCommandLineParser.Object.xHtmlDirectory?.Length > 0)
                    {

                        var outDir = Path.Combine(_fluentCommandLineParser.Object.xHtmlDirectory,
                            $"{DateTimeOffset.UtcNow.ToString("yyyyMMddHHmmss")}_LECmd_Output_for_{_fluentCommandLineParser.Object.xHtmlDirectory.Replace(@":\", "_").Replace(@"\", "_")}");

                        if (Directory.Exists(outDir) == false)
                        {
                            Directory.CreateDirectory(outDir);
                        }

                        File.WriteAllText(Path.Combine(outDir, "normalize.css"), Resources.normalize);
                        File.WriteAllText(Path.Combine(outDir, "style.css"), Resources.style);

                        var outFile = Path.Combine(_fluentCommandLineParser.Object.xHtmlDirectory, outDir, "index.xhtml");

                        _logger.Warn($"Saving HTML output to '{outFile}'");

                        xml = new XmlTextWriter(outFile, Encoding.UTF8)
                        {
                            Formatting = Formatting.Indented,
                            Indentation = 4
                        };

                        xml.WriteStartDocument();

                        xml.WriteProcessingInstruction("xml-stylesheet", "href=\"normalize.css\"");
                        xml.WriteProcessingInstruction("xml-stylesheet", "href=\"style.css\"");

                        xml.WriteStartElement("document");
                    }

                    foreach (var processedFile in _processedFiles)
                    {
                        var o = GetCsvFormat(processedFile);

                        try
                        {
                            csv?.WriteRecord(o);
                        }
                        catch (Exception ex)
                        {
                            _logger.Error(
                                $"Error writing record for '{processedFile.SourceFile}' to '{_fluentCommandLineParser.Object.CsvDirectory}'. Error: {ex.Message}");
                        }

                        if (_fluentCommandLineParser.Object.JsonDirectory?.Length > 0)
                        {
                            SaveJson(processedFile, _fluentCommandLineParser.Object.JsonPretty,
                                _fluentCommandLineParser.Object.JsonDirectory);
                        }

                        //XHTML
                        xml?.WriteStartElement("Container");
                        xml?.WriteElementString("SourceFile", o.SourceFile);
                        xml?.WriteElementString("SourceCreated", o.SourceCreated);
                        xml?.WriteElementString("SourceModified", o.SourceModified);
                        xml?.WriteElementString("SourceAccessed", o.SourceAccessed);

                        xml?.WriteElementString("TargetCreated", o.TargetCreated);
                        xml?.WriteElementString("TargetModified", o.TargetModified);
                        xml?.WriteElementString("TargetAccessed", o.TargetModified);

                        xml?.WriteElementString("FileSize", o.FileSize.ToString());
                        xml?.WriteElementString("RelativePath", o.RelativePath);
                        xml?.WriteElementString("WorkingDirectory", o.WorkingDirectory);
                        xml?.WriteElementString("FileAttributes", o.FileAttributes);
                        xml?.WriteElementString("HeaderFlags", o.HeaderFlags);
                        xml?.WriteElementString("DriveType", o.DriveType);
                        xml?.WriteElementString("DriveSerialNumber", o.DriveSerialNumber);
                        xml?.WriteElementString("DriveLabel", o.DriveLabel);
                        xml?.WriteElementString("LocalPath", o.LocalPath);
                        xml?.WriteElementString("CommonPath", o.CommonPath);
                        xml?.WriteElementString("Arguments", o.Arguments);

                        xml?.WriteElementString("TargetIDAbsolutePath", o.TargetIDAbsolutePath);

                        xml?.WriteElementString("TargetMFTEntryNumber", $"{o.TargetMFTEntryNumber}");
                        xml?.WriteElementString("TargetMFTSequenceNumber", $"{o.TargetMFTSequenceNumber}");

                        xml?.WriteElementString("MachineID", o.MachineID);
                        xml?.WriteElementString("MachineMACAddress", o.MachineMACAddress);
                        xml?.WriteElementString("MACVendor", o.MACVendor);

                        xml?.WriteElementString("TrackerCreatedOn", o.TrackerCreatedOn);

                        xml?.WriteElementString("ExtraBlocksPresent", o.ExtraBlocksPresent);

                        xml?.WriteEndElement();

                        if (_fluentCommandLineParser.Object.XmlDirectory?.Length > 0)
                        {
                            SaveXML(o, _fluentCommandLineParser.Object.XmlDirectory);
                        }
                    }

                    //Close CSV stuff
                    sw?.Flush();
                    sw?.Close();

                    //Close XML
                    xml?.WriteEndElement();
                    xml?.WriteEndDocument();
                    xml?.Flush();
                }
                catch (Exception ex)
                {
                    _logger.Error(
                        $"Error exporting data! Error: {ex.Message}");
                }
            }
            }