Thursday, June 27, 2019

c# Convert a comma separate string into astring array and loop

string fruit = "Apple,Banana,Orange,Strawberry";
string[] split = fruit.Split(',');

foreach (string item in split)
{
    Console.WriteLine(item);
}

Friday, June 21, 2019

c# Create Datatable



 public static DataTable CreateDataTable()
        {

            DataTable dt = new DataTable();

            DataColumn col1 = new DataColumn("FirstName");
            DataColumn col2 = new DataColumn("LastName");
            DataColumn col3 = new DataColumn("Age");

            col1.DataType = System.Type.GetType("System.String");
            col2.DataType = System.Type.GetType("System.String");
            col3.DataType = System.Type.GetType("System.String");

            dt.Columns.Add(col1);
            dt.Columns.Add(col2);
            dt.Columns.Add(col3);

            DataRow row1 = dt.NewRow();
            row1[col1] = "Bob";
            row1[col2] = "Smith";
            row1[col3] = "47";
            dt.Rows.Add(row1);

            DataRow row2 = dt.NewRow();
            row2[col1] = "Tina";
            row2[col2] = "Smith";
            row2[col3] = "34";
            dt.Rows.Add(row2);

            DataRow row3 = dt.NewRow();
            row3[col1] = "Maria";
            row3[col2] = "Smith";
            row3[col3] = "27";
            dt.Rows.Add(row3);

            return dt;

        }

c# add Colunm to Datatable and populate with same value



        public static void AddColunmToDataTable(DataTable dt, string colunmName, string colunmValue)
        {
            dt.Columns.Add(colunmName, typeof(System.String));
            foreach (DataRow row in dt.Rows)
            {
                row[colunmName] = colunmValue;
            }
        }

Thursday, June 20, 2019

c# remove last row on a datatable

c# remove last row on a datatable

dt.Rows.RemoveAt(dt.Rows.Count - 1)

SQL - script to generate c# class



SELECT 
Name,
Case system_type_id
WHEN 127 THEN 'long'
WHEN 56 THEN 'int'
WHEN 60 THEN 'decimal'
WHEN 106 THEN 'decimal'
WHEN 61 THEN 'DateTime'
WHEN 104 THEN 'bool'
WHEN 165 THEN 'byte[]'
WHEN 108 THEN 'double'
WHEN 231 THEN 'string'
WHEN 99 THEN 'string'
WHEN 239 THEN 'string'
WHEN 167 THEN 'string'
when 62 then 'decimal'
ELSE 'ukn:'+CAST(system_type_id AS NVARCHAR(10))
END As [Type],
system_type_id,
'[DataField("' + name +  '")] ' +
+ 'public '+ Case system_type_id
WHEN 127 THEN 'long'
WHEN 56 THEN 'int'
WHEN 60  THEN 'decimal'
WHEN 106 THEN 'decimal'
WHEN 61 THEN 'DateTime'
WHEN 104 THEN 'bool'
WHEN 165 THEN 'byte[]'
WHEN 108 THEN 'double'
WHEN 231 THEN 'string'
WHEN 99 THEN 'string'
WHEN 239 THEN 'string'
WHEN 167 THEN 'string'
when 62 then 'decimal'
ELSE 'ukn:'+CAST(system_type_id AS NVARCHAR(10))
END + ' '+ replace(replace(replace(name, ' ','_'), '-','_'), '''','_') + ' { get; set; }'
AS Code,
'public '+ Case system_type_id
WHEN 127 THEN 'long'
WHEN 56 THEN 'int'
WHEN 60  THEN 'decimal'
WHEN 106 THEN 'decimal'
WHEN 61 THEN 'DateTime'
WHEN 104 THEN 'bool'
WHEN 165 THEN 'byte[]'
WHEN 108 THEN 'double'
WHEN 231 THEN 'string'
WHEN 99 THEN 'string'
WHEN 239 THEN 'string'
WHEN 167 THEN 'string'
when 62 then 'decimal'
ELSE 'ukn:'+CAST(system_type_id AS NVARCHAR(10))
END + ' '+ replace(replace(replace(name, ' ','_'), '-','_'), '''','_') + ' { get; set; }'
AS CodeClass
from Sys.columns where [OBJECT_ID]=OBJECT_ID('[DRIVERSMASTER]')

Wednesday, June 19, 2019

c# SFTP download all files



        public static void DownloadAllFile()
        {
            try
            {
                string host = Properties.Settings.Default.SFTP;
                string username = Properties.Settings.Default.SFTP_UserName;
                string password = Properties.Settings.Default.SFTP_Password;

                string remoteDirectory = Properties.Settings.Default.SFTP_Path;
               
                string downloadDirectory = Properties.Settings.Default.DownloadDirectory;


                using (SftpClient sftp = new SftpClient(host, username, password))
                {
                    try
                    {
                        sftp.Connect();
                        var files = sftp.ListDirectory(remoteDirectory);

                        foreach (var file in files)
                        {
                            string fileName = file.Name;
                            if (fileName.Length > 2)
                            {
                                //Only download file if the file name begins with XX
                                if (fileName.Substring(0, 2) == "XX")
                                {
                                    Console.WriteLine(file.Name);
                                    using (Stream fileStream = File.OpenWrite(downloadDirectory + file.Name))
                                    {
                                        sftp.DownloadFile(file.FullName, fileStream);
                                    }
                                }
                            }
                        }

                        sftp.Disconnect();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("An exception has been caught " + e.ToString());
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("General Exception: {0}", e);
            }
        }

c# SFTP List all Files

This method will list all files in SFTP.

using Renci.SshNet;

    public static void ListFiles()
        {
            try
            {
                string host = Properties.Settings.Default.SFTP;
                string username = Properties.Settings.Default.SFTP_UserName;
                string password = Properties.Settings.Default.SFTP_Password;

                string remoteDirectory = Properties.Settings.Default.SFTP_Path;

                using (SftpClient sftp = new SftpClient(host, username, password))
                {
                    try
                    {
                        sftp.Connect();
                        var files = sftp.ListDirectory(remoteDirectory);

                        foreach (var file in files)
                        {
                            Console.WriteLine(file.Name);
                        }

                        sftp.Disconnect();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("An exception has been caught " + e.ToString());

                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("General Exception: {0}", e);
            }
        }

c# Method to send email with attachment



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net.Mime;

namespace SendEmail
{
    public class SMTPHelper
    {

        //SMTP for email - set these up in project --> Property --> Settings (app.config)
        public static string _SmtpServer;
        public static int _SmtpPort;
        public static Boolean _SmtpIsAuthenticated;
        public static string _SmtpUserName;
        public static string _SmtpPassword;
        public static string _SmtpDomain;

        public static string _SmtpFrom;
        public static string _SmtpDefaultTo;
        public static string _DebugTo;
        public static bool _isDebug;

        public SMTPHelper()
        {

            _SmtpServer = Properties.Settings.Default.smtpServer;
            _SmtpPort = Properties.Settings.Default.smtpPort;
            _SmtpIsAuthenticated = Properties.Settings.Default.smtpIsAuthenticated;
            _SmtpUserName = Properties.Settings.Default.smtpUserName;
            _SmtpPassword = Properties.Settings.Default.smtpPassword;
            _SmtpDomain = Properties.Settings.Default.smtpDomain;


            _SmtpFrom = Properties.Settings.Default.smtpFrom;
            _SmtpDefaultTo = Properties.Settings.Default.smtpDefaultTo;

            _DebugTo = Properties.Settings.Default.smtpDebugTo;
            _isDebug = Properties.Settings.Default.DebugMode;



        }

        public string SendEmail(string emailAddresses, string subject, string message, string submessage, bool isHighPriority, string fileToAttach)
        {
            string retObj = null;
            try
            {

                //emailAddresses = (emailAddresses == "" || emailAddresses == null) ? _SmtpDefaultTo : emailAddresses;
                System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                msg.Subject = subject;
                string toAddress = (_isDebug) ? _DebugTo : emailAddresses;
                string[] toArray = toAddress.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in toArray)
                {
                    msg.To.Add(item);
                }


                msg.From = new System.Net.Mail.MailAddress(_SmtpFrom);
                msg.IsBodyHtml = true;
                msg.Body = message + "<p> " + submessage + "</p>";
                if (_isDebug)
                {
                    msg.Body += "<h3>Debug Mode is On. <br/> Intended Email Addresses: " + emailAddresses + "</h3>";
                }
                //msg.Body += (ex == null) ? "" : ex.ToString();
                //msg.AlternateViews.Add(view);

                msg.Priority = (isHighPriority) ? System.Net.Mail.MailPriority.High : System.Net.Mail.MailPriority.Normal;
                msg.IsBodyHtml = true;
                Attachment data = new Attachment(fileToAttach, MediaTypeNames.Application.Octet);
                msg.Attachments.Add(data);
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(_SmtpServer);
                smtp.Port = _SmtpPort;

                if (_SmtpIsAuthenticated)
                {
                    smtp.Credentials = new System.Net.NetworkCredential(_SmtpUserName, _SmtpPassword, _SmtpDomain);
                }

                smtp.Send(msg);

            }
            catch (Exception e)
            {
                // log the exception
                retObj = e.ToString();
                string errorStr = "General Exception Email: " + e.ToString();
                Utility.LogWrite(errorStr);
                Console.WriteLine("General Exception Email: {0}", e);
            }

            return retObj;
        }
    }
}

c# utility to log in a text file



using System.IO;

//Loggin
public static string LogFilePath;
public static bool DebugMode;

LogFilePath = Properties.Settings.Default.LogFilePath;
DebugMode = Properties.Settings.Default.DebugMode;

        public static void LogWrite(string logText)
        {

            if (GlobalVars.DebugMode)
            {
                // check to see if the directory exists
                FileInfo logFile = new FileInfo(GlobalVars.LogFilePath);
                if (!logFile.Directory.Exists)
                {
                    logFile.Directory.Create();
                }

                logText = Environment.NewLine + DateTime.Now + " - " + logText;
                File.AppendAllText(GlobalVars.LogFilePath, logText);
            }
        }

c# Convert a non delimited txt file to a DataTable

This a a way to convert a non delimited txt file into a DataTable. First you would need another table with the definition of the file.  The table below would be the DataTable dt_Definition mentioned on the method below.

FieldType ReportColunmName Begin Length Order
Detail Last Name 1 30 1
Detail First Name 31 20 2
Detail Middle Initial 51 1 3
Detail Address 52 60 4
Detail City 112 30 5
Detail State 142 2 6
Detail Zip 144 10 7
Detail Phone AreaCode 154 3 8
Detail Phone 157 8 9
Detail Phone Ext 164 4 10
Detail Hope Phone 169 15 11
Detail Date of Birth 184 10 12
Detail Sex 194 1 13
Detail SSN 195 9 14

using System.IO;
using System.Data;

        static DataTable ConvertTxtFileToDataTable(string dataFile, DataTable dt_Definition)
        {
            DataTable retObj = new DataTable();
            try
            {
                //Add colunms
                foreach (DataRow row in dt_Definition.Rows)
                {
                    string reportColunmName = row["ReportColunmName"].ToString().Trim();
                    string recordType = row["FieldType"].ToString();
                    Int32 order = Int32.Parse(row["Order"].ToString());

                    if (order > 0 && recordType == "Detail")
                    {
                        retObj.Columns.Add(new DataColumn(reportColunmName, typeof(string)));
                    }
                }

                //Add rows
                bool isFirstLine = true;
                var lines = File.ReadAllLines(dataFile);
                foreach (string line in lines)
                {

                    string currentLine = line;

                    if (isFirstLine == false)
                    {
                        DataRow newRow = retObj.NewRow();
                        foreach (DataRow defRow in dt_Definition.Rows)
                        {

                            Int32 begin = Int32.Parse(defRow["Begin"].ToString()) - 1;
                            Int32 lenght = Int32.Parse(defRow["Length"].ToString());
                            string ReportColunmName = defRow["ReportColunmName"].ToString().Trim();

                            string value = currentLine.Substring(begin, lenght).Trim();
                            newRow[ReportColunmName] = value;
                        }
                        retObj.Rows.Add(newRow);
                    }
                    else
                    {
                        //Skip header row
                        isFirstLine = false;
                    }
                }
            }

            catch (Exception e)
            {
                Console.WriteLine("General Exception: {0}", e);

            }
            return retObj;

        }

c# replace function



string name = "Monica Santana";
string newName= name.Replace("Santana", "Smith");

c# Convert DataTable to CSV File



        static void DataTableToCsvFile(DataTable sourceTable, bool includeHeaders, string destinationCSV)
        {
            try
            {
                StreamWriter writer = new StreamWriter(destinationCSV);
                if (includeHeaders)
                {
                    IEnumerable<String> headerValues = sourceTable.Columns
                        .OfType<DataColumn>()
                        .Select(column => QuoteValue(column.ColumnName));

                    writer.WriteLine(String.Join(",", headerValues));
                }

                IEnumerable<String> items = null;

                foreach (DataRow row in sourceTable.Rows)
                {
                    items = row.ItemArray.Select(o => QuoteValue(o?.ToString() ?? String.Empty));
                    writer.WriteLine(String.Join(",", items));
                }

                writer.Flush();
                writer.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine("General Exception: {0}", e);
            }
        }

c# Convert CSV file to DataTable and sort DataTable


using System.IO;
using System.Data;

        static DataTable ConvertCSVToDataTable(string strFilePath)
        {
            DataTable dt = new DataTable();
            try
            {
                using (StreamReader sr = new StreamReader(strFilePath))
                {
                    //Add headers
                    string[] headers = sr.ReadLine().Split(',');
                    foreach (string header in headers)
                    {
                        dt.Columns.Add(header);
                    }
                    //Add Rows
                    while (!sr.EndOfStream)
                    {
                        string[] rows = sr.ReadLine().Split(',');
                        DataRow dr = dt.NewRow();
                        for (int i = 0; i < headers.Length; i++)
                        {
                            //Add each cell to row
                            dr[i] = rows[i];
                        }
                        //Add row to datatable
                        dt.Rows.Add(dr);
                    }
                }

                //Sort the data table
                dt.DefaultView.Sort = "FieldName";
                dt = dt.DefaultView.ToTable();
            }
            catch (Exception e)
            {
                Console.WriteLine("General Exception: {0}", e);
            }

            return dt;
        }

c# Move file to different directory


using System.IO;

        static void MoveFileToFolder(FileInfo fi)
        {
            try
            {
                string moveToDir = Properties.Settings.Default.MoveToDirectory;
                string fileName = fi.Name;
                string FileAndPath = moveToDir + '/' + fileName;
                if (File.Exists(FileAndPath))
                {
                    File.Delete(FileAndPath);
                }
                fi.MoveTo(FileAndPath);
            }
            catch (Exception e)
            {
                Console.WriteLine("General Exception: {0}", e);

            }

        }

c# - Loop through files in a directory



using System.IO;     
        static void loopThroughDirectory(string sourceDir)
        {
            DirectoryInfo di = new DirectoryInfo(sourceDir);

            //Process each file
            foreach (FileInfo fi in di.GetFiles())
            {
                string fileNameAndPath = fi.FullName;
            }

        }

Saturday, June 8, 2019

Welcome

Hello,

My name is Allie, and I am so excited to start this new blog to share my knowledge in technology and coding.