Tuesday 4 October 2022

SqlDataBaseLibrary

using System;

using System.Collections.Generic;

using System.Data;

using System.Data.SqlClient;

using AOS.Repository.Infrastructure;

using System.Threading.Tasks;

using System.Linq;

using AOS.Repository.Models;

using AOS.Repository.Data;


namespace AOS.Repository.DataServices

{

    public class DatabaseHelper : IDisposable

    {

        private readonly SqlConnection objConnection;


        public static string ConnectionString { get; set; }

        public SqlBulkCopy bulkCopy;

        public bool HasError { get; set; } = false;


        public DatabaseHelper()

        {

            objConnection = new SqlConnection(ConnectionStrings.MainDbConnectionString);

            Command = new SqlCommand

            {

                CommandTimeout = 120,

                Connection = objConnection

            };

        }


        public DatabaseHelper(string strDBConn, bool IsBulCopy = false, bool IsKeepIdentityBulCopy = false)

        {

            objConnection = new SqlConnection(strDBConn);

            Command = new SqlCommand

            {

                CommandTimeout = 120,

                Connection = objConnection

            };

            if (IsBulCopy)

            {

                if (IsKeepIdentityBulCopy)

                {

                    bulkCopy = new SqlBulkCopy(objConnection, SqlBulkCopyOptions.KeepIdentity, null);

                }

                else

                {

                    bulkCopy = new SqlBulkCopy(objConnection, SqlBulkCopyOptions.UseInternalTransaction, null);

                }

            }

        }


        public SqlParameter AddParameter(string name, object value)

        {

            SqlParameter p = Command.CreateParameter();

            p.ParameterName = name;

            p.Value = value;

            if ((p.SqlDbType == SqlDbType.VarChar) || (p.SqlDbType == SqlDbType.NVarChar))

            {

                p.Size = (p.SqlDbType == SqlDbType.VarChar) ? 8000 : 4000;


                if ((value != null) && !(value is DBNull) && (value.ToString().Length > p.Size))

                    p.Size = -1;

            }

            return Command.Parameters.Add(p);

        }


        public SqlParameter AddParameter(string name, object value, ParamType type)

        {

            SqlParameter p = Command.CreateParameter();

            if (type == ParamType.Output)

                p.Direction = ParameterDirection.Output;

            p.ParameterName = name;

            p.Value = value;

            if ((p.SqlDbType == SqlDbType.VarChar) || (p.SqlDbType == SqlDbType.NVarChar))

            {

                p.Size = (p.SqlDbType == SqlDbType.VarChar) ? 8000 : 4000;


                if ((value != null) && !(value is DBNull) && (value.ToString().Length > p.Size))

                    p.Size = -1;

            }

            return Command.Parameters.Add(p);

        }


        public SqlParameter AddParameter(SqlParameter parameter)

        {

            return Command.Parameters.Add(parameter);

        }


        public void ClearParameters()

        {

            Command.Parameters.Clear();

        }


        public SqlCommand Command { get; }


        public bool ExecuteBulkCopy(DataTable dt)

        {

            bool result = false;

            try

            {

                if (objConnection.State == System.Data.ConnectionState.Closed)

                {

                    objConnection.Open();

                }


                bulkCopy.BulkCopyTimeout = 0;


                bulkCopy.WriteToServer(dt);


                result = true;

            }

            catch (Exception ex)

            {

                HandleExceptions(ex, "ExecuteBulkCopy");

            }

            finally

            {

                bulkCopy.Close();


                if (Command.Transaction == null)

                {

                    objConnection.Close();

                }

            }

            return result;

        }


        public void BeginTransaction()

        {

            if (objConnection.State == System.Data.ConnectionState.Closed)

            {

                objConnection.Open();

            }

            Command.Transaction = objConnection.BeginTransaction();

        }


        public void CommitTransaction()

        {

            Command.Transaction.Commit();

            objConnection.Close();

        }


        public void RollbackTransaction()

        {

            Command.Transaction.Rollback();

            objConnection.Close();

        }


        public int ExecuteNonQuery(string query)

        {

            return ExecuteNonQuery(query, CommandType.Text);

        }


        public int ExecuteNonQuery(string query, CommandType commandtype, SqlParameter[] para = null)

        {

            Command.CommandText = query;

            Command.CommandType = commandtype;

            if (para?.Length > 0)

            {

                Command.Parameters.AddRange(para);

            }

            int i = -1;

            try

            {

                if (objConnection.State == System.Data.ConnectionState.Closed)

                {

                    objConnection.Open();

                }

                i = Command.ExecuteNonQuery();

            }

            catch (Exception ex)

            {

                SqlException sx = (SqlException)ex;

                if (sx.Number == 547)       // Foreign Key Error

                    i = sx.Number;

                else

                    HandleExceptions(ex, query);

            }

            finally

            {

                //objCommand.Parameters.Clear();

                if (Command.Transaction == null)

                {

                    objConnection.Close();

                }

            }

            return i;

        }


        public string ExecuteNonQuery(string query, CommandType commandtype, string outputparam)

        {

            Command.CommandText = query;

            Command.CommandType = commandtype;

            string outputParamValue = "";

            int i;

            try

            {

                if (objConnection.State == System.Data.ConnectionState.Closed)

                {

                    objConnection.Open();

                }

                i = Command.ExecuteNonQuery();

                outputParamValue = Command.Parameters[outputparam].Value.ToString();

            }

            catch (Exception ex)

            {

                SqlException sx = (SqlException)ex;

                if (sx.Number == 547)       // Foreign Key Error

                {

                    i = sx.Number;

                }

                else

                {

                    Command.Transaction.Rollback();

                    HandleExceptions(ex, query);

                }

            }

            finally

            {

                //objCommand.Parameters.Clear();

                if (Command.Transaction == null)

                {

                    objConnection.Close();

                }

            }

            return outputParamValue;

        }


        public object ExecuteScalar(string query)

        {

            return ExecuteScalar(query, CommandType.Text);

        }


        public object ExecuteScalar(string query, CommandType commandtype, SqlParameter[] para = null)

        {

            Command.CommandText = query;

            Command.CommandType = commandtype;

            if (para?.Length > 0)

            {

                Command.Parameters.AddRange(para);

            }

            object o = null;

            try

            {

                if (objConnection.State == System.Data.ConnectionState.Closed)

                {

                    objConnection.Open();

                }

                o = Command.ExecuteScalar();

            }

            catch (Exception ex)

            {

                HandleExceptions(ex, query);

            }

            finally

            {

                //objCommand.Parameters.Clear();

                if (Command.Transaction == null)

                {

                    objConnection.Close();

                }

            }

            return o;

        }


        #region ExecuteScalarAsync


        public async static Task<object> ExecuteScalarAsync(string commandText, CommandType commandType = CommandType.StoredProcedure, params SqlParameter[] commandParameters)

        {

            if (string.IsNullOrEmpty(ConnectionStrings.MainDbConnectionString)) throw new ArgumentNullException("connectionString");

            using (var connection = new SqlConnection(ConnectionStrings.MainDbConnectionString))

            {

                await connection.OpenAsync().ConfigureAwait(false);

                var cmd = new SqlCommand

                {

                    CommandTimeout = 180

                };

                var mustCloseConnection = await PrepareCommandAsync(cmd, connection, null, commandType, commandText, commandParameters).ConfigureAwait(false);

                var retval = await cmd.ExecuteScalarAsync().ConfigureAwait(false);

                cmd.Parameters.Clear();

                if (mustCloseConnection)

                    connection.Close();

                return retval;

            }

        }

        public async static Task<int> ExecuteNonQueryAsync(string commandText, CommandType commandType = CommandType.StoredProcedure, SqlParameter[] commandParameters=null)

        {

            if (string.IsNullOrEmpty(ConnectionStrings.MainDbConnectionString)) throw new ArgumentNullException("connectionString");

            using (var connection = new SqlConnection(ConnectionStrings.MainDbConnectionString))

            {

                await connection.OpenAsync().ConfigureAwait(false);

                var cmd = new SqlCommand

                {

                    CommandTimeout = 180

                };

                var mustCloseConnection = await PrepareCommandAsync(cmd, connection, null, commandType, commandText, commandParameters).ConfigureAwait(false);

                var retval = await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);

                cmd.Parameters.Clear();

                if (mustCloseConnection)

                    connection.Close();

                return retval;

            }

        }


        public static async Task SaveLogsAsync(int UserId,string Username,DataTable UpdatedData)

        {

            if (UpdatedData.Rows.Count > 0)

            {

                SqlParameter[] LogParams=new SqlParameter[3];

                LogParams[0]= new SqlParameter("@UserName", Username);

                LogParams[1]=new SqlParameter("@UserId", UserId);

                LogParams[2]=new SqlParameter{SqlDbType = System.Data.SqlDbType.Structured,ParameterName = "@AuditTable",Value = UpdatedData};

                if (string.IsNullOrEmpty(ConnectionStrings.LogDbConnectionString)) throw new ArgumentNullException("connectionString");

                using (var connection = new SqlConnection(ConnectionStrings.LogDbConnectionString))

                {

                    await connection.OpenAsync().ConfigureAwait(false);

                    var cmd = new SqlCommand

                    {

                        CommandTimeout = 180

                    };

                    var mustCloseConnection = await PrepareCommandAsync(cmd, connection, null, CommandType.StoredProcedure, "IUDAudit", LogParams).ConfigureAwait(false);

                    await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);

                    cmd.Parameters.Clear();

                    if (mustCloseConnection)

                        connection.Close();

                }

            }

        }

        public static async Task<string> SaveAMAWaitTime(WaitTimeSaveModel model)

        {

            SqlParameter parm = new SqlParameter("@ReturnValue", SqlDbType.VarChar, 100)

            {

                Direction = ParameterDirection.Output

            };

            SqlParameter[] para = {

                    new SqlParameter("@ID", model.Code),

                    new SqlParameter("@WaitTime", model.WaitTime),

                    new SqlParameter("@ReasonCode", model.ReasonCode),

                    new SqlParameter("@StartDate", model.Start),

                    new SqlParameter("@EndDate", model.End),

                    parm

                };

                if (string.IsNullOrEmpty(ConnectionStrings.AMADbConnectionString)) throw new ArgumentNullException("connectionString");

                using (var connection = new SqlConnection(ConnectionStrings.AMADbConnectionString))

                {

                    var cmd = new SqlCommand

                    {

                        CommandTimeout = 180

                    };

                    var mustCloseConnection = await PrepareCommandAsync(cmd, connection, null, CommandType.StoredProcedure, "AOS_INSERT_WAITTIME_HISTORY",para).ConfigureAwait(false);

                    await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);

                    cmd.Parameters.Clear();

                    if (mustCloseConnection)

                        connection.Close();

                }

                return  Convert.ToString(para[5].Value);

        }

        #endregion ExecuteScalarAsync        


        public SqlDataReader ExecuteReader(string query)

        {

            return ExecuteReader(query, CommandType.Text);

        }


        public SqlDataReader ExecuteReader(string query, CommandType commandtype)

        {

            Command.CommandText = query;

            Command.CommandType = commandtype;

            SqlDataReader reader = null;

            try

            {

                if (objConnection.State == System.Data.ConnectionState.Closed)

                {

                    objConnection.Open();

                }

                reader = Command.ExecuteReader(CommandBehavior.CloseConnection);

            }

            catch (Exception ex)

            {

                HandleExceptions(ex, query);

            }

            finally

            {

                //objCommand.Parameters.Clear();

                if (Command.Transaction == null)

                {

                    objConnection.Close();

                }

            }

            return reader;

        }


        public DataSet ExecuteDataSet(string query)

        {

            return ExecuteDataSet(query, CommandType.Text);

        }


        public DataSet ExecuteDataSet(string query, CommandType commandtype)

        {

            SqlDataAdapter adapter = new SqlDataAdapter();

            Command.CommandText = query;

            Command.CommandType = commandtype;

            adapter.SelectCommand = Command;

            DataSet ds = new DataSet();

            try

            {

                adapter.Fill(ds);

            }

            catch (Exception ex)

            {

                HandleExceptions(ex, query);

            }

            finally

            {

                //objCommand.Parameters.Clear();

                if (Command.Transaction == null)

                {

                    objConnection.Close();

                }

            }

            return ds;

        }


        public DataSet FetchDataSetBySP(string Spname, SqlParameter[] para)

        {

            DataSet ds = new DataSet();

            Command.CommandType = CommandType.StoredProcedure;

            Command.Parameters.AddRange(para);

            Command.CommandText = Spname;

            SqlDataAdapter da = new SqlDataAdapter(Command);

            try

            {

                objConnection.Open();

                da.Fill(ds);

                return ds;

            }

            catch (Exception ex)

            {

                HandleExceptions(ex, Spname);

            }

            finally

            {

                //objCommand.Parameters.Clear();

                if (Command.Transaction == null)

                {

                    objConnection.Close();

                }

            }

            return ds;

        }


        #region ExecuteDataTableAsync

        private static void AttachParameters(SqlCommand command, IEnumerable<SqlParameter> commandParameters)

        {

            if (command == null) throw new ArgumentNullException(nameof(command));

            if (commandParameters == null) return;

            foreach (var p in commandParameters.Where(p => p != null))

            {

                if ((p.Direction == ParameterDirection.InputOutput ||

                     p.Direction == ParameterDirection.Input) &&

                    (p.Value == null))

                {

                    p.Value = DBNull.Value;

                }

                command.Parameters.Add(p);

            }

        }

        private async static Task<bool> PrepareCommandAsync(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, IEnumerable<SqlParameter> commandParameters)

        {

            if (command == null) throw new ArgumentNullException(nameof(command));

            if (string.IsNullOrEmpty(commandText)) throw new ArgumentNullException(nameof(commandText));

            var mustCloseConnection = false;

            if (connection.State != ConnectionState.Open)

            {

                mustCloseConnection = true;

                await connection.OpenAsync().ConfigureAwait(false);

            }

            command.Connection = connection;

            command.CommandText = commandText;

            if (transaction != null)

            {

                if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", nameof(transaction));

                command.Transaction = transaction;

            }

            command.CommandType = commandType;

            if (commandParameters != null)

            {

                AttachParameters(command, commandParameters);

            }

            return mustCloseConnection;

        }


        public async static Task<DataSet> FetchAuditLogAsync(string commandText, params SqlParameter[] commandParameters)

        {

           if (string.IsNullOrEmpty(ConnectionStrings.LogDbConnectionString)) throw new ArgumentNullException("connectionString");

            using (var connection = new SqlConnection(ConnectionStrings.LogDbConnectionString))

            {

                await connection.OpenAsync().ConfigureAwait(false);

                var cmd = new SqlCommand

                {

                    CommandTimeout = 180

                };

                var mustCloseConnection = await PrepareCommandAsync(cmd, connection, null, CommandType.StoredProcedure, commandText, commandParameters).ConfigureAwait(false);

                using (var da = new SqlDataAdapter(cmd))

                {

                    var ds = new DataSet();

                    da.Fill(ds);

                    cmd.Parameters.Clear();

                    if (mustCloseConnection)

                        connection.Close();

                    return ds;

                }

            }

        }


        public async static Task<DataTable> FetchAuditLogByQryAsync(string commandText, params SqlParameter[] commandParameters)

        {

           if (string.IsNullOrEmpty(ConnectionStrings.LogDbConnectionString)) throw new ArgumentNullException("connectionString");

            using (var connection = new SqlConnection(ConnectionStrings.LogDbConnectionString))

            {

                await connection.OpenAsync().ConfigureAwait(false);

                var cmd = new SqlCommand

                {

                    CommandTimeout = 180

                };

                var mustCloseConnection = await PrepareCommandAsync(cmd, connection, null, CommandType.Text, commandText, commandParameters).ConfigureAwait(false);

                using (var da = new SqlDataAdapter(cmd))

                {

                    var dt = new DataTable();

                    da.Fill(dt);

                    cmd.Parameters.Clear();

                    if (mustCloseConnection)

                        connection.Close();

                    return dt;

                }

            }

        }


        public async static Task<ApiLogMaster> FetchSingleApiLogQryAsync(string commandText,int Id)

        {


            ApiLogMaster obj = new ApiLogMaster();

            SqlParameter[] para = { new SqlParameter("@Id", Id) };

           

            try

            {

                if (string.IsNullOrEmpty(ConnectionStrings.LogDbConnectionString)) throw new ArgumentNullException("connectionString");

                using (var connection = new SqlConnection(ConnectionStrings.LogDbConnectionString))

            {

                await connection.OpenAsync().ConfigureAwait(false);

                var cmd = new SqlCommand

                {

                    CommandTimeout = 180

                };

                var mustCloseConnection = await PrepareCommandAsync(cmd, connection, null, CommandType.StoredProcedure, commandText, para).ConfigureAwait(false);

                using (var da = new SqlDataAdapter(cmd))

                {

                    var dt = new DataTable();

                    da.Fill(dt);

                    cmd.Parameters.Clear();

                    if (mustCloseConnection)

                        connection.Close();

                    if ((dt?.Rows?.Count ?? 0) > 0)

                    {

                        if (dt.Rows[0]["AppId"] != DBNull.Value)

                        {

                            obj.AppId = dt.Rows[0]["AppId"].ToInt();

                        }

                        if (dt.Rows[0]["AppName"] != DBNull.Value)

                        {

                            obj.AppName = dt.Rows[0]["AppName"].ToString();

                        }

                        if (dt.Rows[0]["EndPoint"] != DBNull.Value)

                        {

                            obj.EndPoint = dt.Rows[0]["EndPoint"].ToString();

                        }

                        if (dt.Rows[0]["Request"] != DBNull.Value)

                        {

                            obj.Request = dt.Rows[0]["Request"].ToString();

                        }

                        if (dt.Rows[0]["Response"] != DBNull.Value)

                        {

                            obj.Response = dt.Rows[0]["Response"].ToString();

                        }

                        if (dt.Rows[0]["Error"] != DBNull.Value)

                        {

                            obj.Error = dt.Rows[0]["Error"].ToString();

                        }

                        if (dt.Rows[0]["CreatedDate"] != DBNull.Value)

                        {

                            obj.CreatedDate = Convert.ToDateTime(dt.Rows[0]["CreatedDate"]);

                        }

                    }

                }

            }

            }

            catch(Exception ex)

            {


            }

            return obj;

        }


        



        public async static Task<DataSet> FetchDataSetBySPAsync(string commandText, params SqlParameter[] commandParameters)

        {

           if (string.IsNullOrEmpty(ConnectionStrings.MainDbConnectionString)) throw new ArgumentNullException("connectionString");

            using (var connection = new SqlConnection(ConnectionStrings.MainDbConnectionString))

            {

                await connection.OpenAsync().ConfigureAwait(false);

                var cmd = new SqlCommand

                {

                    CommandTimeout = 180

                };

                var mustCloseConnection = await PrepareCommandAsync(cmd, connection, null, CommandType.StoredProcedure, commandText, commandParameters).ConfigureAwait(false);

                using (var da = new SqlDataAdapter(cmd))

                {

                    var ds = new DataSet();

                    da.Fill(ds);

                    cmd.Parameters.Clear();

                    if (mustCloseConnection)

                        connection.Close();

                    return ds;

                }

            }

        }


        #endregion ExecuteDatasetAsync 


        public DataTable FetchDataTableBySP(string Spname, SqlParameter[] para)

        {

            DataTable dt = new DataTable();

            Command.CommandType = CommandType.StoredProcedure;

            Command.Parameters.AddRange(para);

            Command.CommandText = Spname;

            SqlDataAdapter da = new SqlDataAdapter(Command);

            try

            {

                objConnection.Open();

                da.Fill(dt);

                return dt;

            }

            catch (Exception ex)

            {

                HandleExceptions(ex, Spname);

            }

            finally

            {

                //objCommand.Parameters.Clear();

                if (Command.Transaction == null)

                {

                    objConnection.Close();

                }

            }

            return dt;

        }


        public DataTable FetchDataTableByQuery(string Qry, SqlParameter[] para = null)

        {

            DataTable dt = new DataTable();

            Command.CommandType = CommandType.Text;

            if (para != null)

                Command.Parameters.AddRange(para);

            Command.CommandText = Qry;

            SqlDataAdapter da = new SqlDataAdapter(Command);

            try

            {

                objConnection.Open();

                da.Fill(dt);

                return dt;

            }

            catch (Exception ex)

            {

                HandleExceptions(ex, Qry);

            }

            finally

            {

                //objCommand.Parameters.Clear();

                if (Command.Transaction == null)

                {

                    objConnection.Close();

                }

            }

            return dt;

        }


        #region ExecuteDataTableAsync


        public async static Task<DataTable> FetchDataTableBySPAsync(string commandText,  params SqlParameter[] commandParameters)

        {

            if (string.IsNullOrEmpty(ConnectionStrings.MainDbConnectionString)) throw new ArgumentNullException("connectionString");

            using (var connection = new SqlConnection(ConnectionStrings.MainDbConnectionString))

            {

                DataTable dt = new DataTable();

                var cmd = new SqlCommand

                {

                    CommandTimeout = 180

                };

                await PrepareCommandAsync(cmd, connection, null, CommandType.StoredProcedure, commandText, commandParameters).ConfigureAwait(false);

                var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false);

                dt.Load(reader);

                return dt;

            }

        }


        public async static Task<DataTable> FetchDataTableByQueryAsync(string commandText,  params SqlParameter[] commandParameters)

        {

            if (string.IsNullOrEmpty(ConnectionStrings.MainDbConnectionString)) throw new ArgumentNullException("connectionString");

            using (var connection = new SqlConnection(ConnectionStrings.MainDbConnectionString))

            {

                DataTable dt = new DataTable();

                var cmd = new SqlCommand

                {

                    CommandTimeout = 180

                };

                await PrepareCommandAsync(cmd, connection, null, CommandType.Text, commandText, commandParameters).ConfigureAwait(false);

                var reader = await cmd.ExecuteReaderAsync().ConfigureAwait(false);

                dt.Load(reader);

                return dt;

            }

        }


        #endregion ExecuteDatasetAsync 


        public List<T> FetchListBySP<T>(string Spname, SqlParameter[] para)

        {

            List<T> lst = new List<T>();

            Command.CommandType = CommandType.StoredProcedure;

            Command.Parameters.AddRange(para);

            Command.CommandText = Spname;

            try

            {

                objConnection.Open();

                var dr = Command.ExecuteReader();

                while (dr.Read())

                {

                    T item = CommonFunctions.GetListItem<T>(dr);

                    lst.Add(item);

                }

                return lst;

            }

            catch (Exception ex)

            {

                HandleExceptions(ex, Spname);

            }

            finally

            {

                //objCommand.Parameters.Clear();

                if (Command.Transaction == null)

                {

                    objConnection.Close();

                }

            }

            return lst;

        }


        public List<T> FetchListByQuery<T>(string Qry, SqlParameter[] para = null)

        {

            List<T> lst = new List<T>();

            Command.CommandType = CommandType.Text;

            Command.Parameters.AddRange(para);

            Command.CommandText = Qry;

            try

            {

                objConnection.Open();

                var dr = Command.ExecuteReader();

                while (dr.Read())

                {

                    T item = CommonFunctions.GetListItem<T>(dr);

                    lst.Add(item);

                }

                return lst;

            }

            catch (Exception ex)

            {

                HandleExceptions(ex, Qry);

            }

            finally

            {

                //objCommand.Parameters.Clear();

                if (Command.Transaction == null)

                {

                    objConnection.Close();

                }

            }

            return lst;

        }


        #region ExecuteTAsync        


        public async static Task<List<T>> FetchListBySPAsync<T>(string commandText, params SqlParameter[] commandParameters)

        {

            if (string.IsNullOrEmpty(ConnectionStrings.MainDbConnectionString)) throw new ArgumentNullException("connectionString");

            using (var connection = new SqlConnection(ConnectionStrings.MainDbConnectionString))

            {

                var cmd = new SqlCommand

                {

                    CommandTimeout = 180

                };

                await PrepareCommandAsync(cmd, connection, null, CommandType.StoredProcedure, commandText, commandParameters).ConfigureAwait(false);

                var dr = await cmd.ExecuteReaderAsync().ConfigureAwait(false);

                List<T> lst = new List<T>();

                while (await dr.ReadAsync().ConfigureAwait(false))

                {

                        T item = CommonFunctions.GetListItem<T>(dr);

                        lst.Add(item);

                }

                return lst;

            }

        }


        public async static Task<List<T>> FetchListByQueryAsync<T>(string commandText, params SqlParameter[] commandParameters)

        {

            if (string.IsNullOrEmpty(ConnectionStrings.MainDbConnectionString)) throw new ArgumentNullException("connectionString");

            using (var connection = new SqlConnection(ConnectionStrings.MainDbConnectionString))

            {

                var cmd = new SqlCommand

                {

                    CommandTimeout = 180

                };

                await PrepareCommandAsync(cmd, connection, null, CommandType.Text, commandText, commandParameters).ConfigureAwait(false);

                var dr = await cmd.ExecuteReaderAsync().ConfigureAwait(false);

                List<T> lst = new List<T>();

                while (await dr.ReadAsync().ConfigureAwait(false))

                {

                        T item = CommonFunctions.GetListItem<T>(dr);

                        lst.Add(item);

                }

                return lst;

            }

        }


        #endregion ExecuteDatasetAsync 


        public DataSet SpExecuteDataSet(string SpName, SqlParameter[] parameter)

        {

            SqlDataAdapter adapter = new SqlDataAdapter();

            Command.CommandText = SpName;

            Command.CommandType = CommandType.StoredProcedure;

            foreach (SqlParameter sParam in parameter)

            {

                Command.Parameters.Add(sParam);

            }

            adapter.SelectCommand = Command;

            DataSet ds = new DataSet();

            try

            {

                adapter.Fill(ds);

            }

            catch (Exception ex)

            {

                HandleExceptions(ex, SpName);

            }

            finally

            {

                //objCommand.Parameters.Clear();

                if (Command.Transaction == null)

                {

                    objConnection.Close();

                }

            }

            return ds;

        }


        private void HandleExceptions(Exception ex, string query)

        {

            HasError = true;

            WriteToLog(ex.Message, query);

        }


        private void WriteToLog(string msg, string query)

        {

            if (query == null)

                throw new ArgumentNullException(nameof(query));


            if (msg == null)

                throw new ArgumentNullException(nameof(msg));


            try

            {

                /*string strLogFile = CurrentContext.Config.UploadPath + "Logfile.txt";

                if (strLogFile != "")

                {

                    System.IO.StreamWriter writer = System.IO.File.AppendText(strLogFile);

                    writer.WriteLine("Date and Time : " + DateTime.Now.ToString() + " - " + msg);

                    writer.WriteLine("Error in Query : " + query);

                    writer.WriteLine("");

                    writer.Close();

                }*/

            }

            catch { }

        }


        public void Dispose()

        {

            Command.Parameters.Clear();

            objConnection.Close();

            objConnection.Dispose();

            Command.Dispose();

        }


        public enum ParamType

        {

            Input, Output, InputOutput

        }

    }

}


Tuesday 23 August 2022

Amazon S3 Bucket ( Wirte,Read,Delete files)

 using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net.Http;

using System.Net.Http.Headers;

using System.Threading.Tasks;

using Amazon.S3;

using Amazon.S3.Model;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Http;

using Microsoft.Extensions.Configuration;

using Newtonsoft.Json;

using SafetyHub.Api.Infrastructure.Config;

using SafetyHub.Api.Infrastructure.ExtensionMethods;


namespace SafetyHub.Api.Infrastructure.Helper

{

    public class AwsS3 : IAwsS3

    {

        public async Task<(bool IsSuccess, string Result)> WriteFile(IFormFile file, string keyName)

        {

            string extension = Path.GetExtension(file.FileName);

            var filePath = keyName + "_" + DateTime.UtcNow.Ticks + extension;


            using var newMemoryStream = new MemoryStream();

            await file.CopyToAsync(newMemoryStream).ConfigureAwait(false);

            var request = new PutObjectRequest

            {

                InputStream = newMemoryStream,

                BucketName = Configs.AWSConfigurations.S3BucketName,

                Key = filePath

            };

            var _s3Client = new AmazonS3Client(Configs.AWSConfigurations.AWSAccessKey, Configs.AWSConfigurations.AWSSecretKey, new AmazonS3Config() { ServiceURL = Configs.AWSConfigurations.S3ServiceURL });

            var response = await _s3Client.PutObjectAsync(request).ConfigureAwait(false);

            if (response?.HttpStatusCode.Equals(System.Net.HttpStatusCode.OK) == true)

            {

                return (true, filePath);

            }

            return (false, Constant.HttpResponse.ERROR);

        }


        public async Task<(bool IsSuccess, Stream Result)> ReadFile(string keyName)

        {

            try

            {

                var request = new GetObjectRequest

                {

                    BucketName = Configs.AWSConfigurations.S3BucketName,

                    Key = keyName

                };

                var _s3Client = new AmazonS3Client(Configs.AWSConfigurations.AWSAccessKey, Configs.AWSConfigurations.AWSSecretKey, new AmazonS3Config() { ServiceURL = Configs.AWSConfigurations.S3ServiceURL });

                var response = await _s3Client.GetObjectAsync(request).ConfigureAwait(false);

                if (response?.HttpStatusCode.Equals(System.Net.HttpStatusCode.OK) == true)

                {

                    return (true, response.ResponseStream);

                }

            }

            catch { }

            return (false, null);

        }


        public async Task<(bool IsSuccess, string Result)> DeleteFile(string keyName)

        {

            var request = new DeleteObjectRequest

            {

                BucketName = Configs.AWSConfigurations.S3BucketName,

                Key = keyName

            };

            var _s3Client = new AmazonS3Client(Configs.AWSConfigurations.AWSAccessKey, Configs.AWSConfigurations.AWSSecretKey, new AmazonS3Config() { ServiceURL = Configs.AWSConfigurations.S3ServiceURL });

            var response = await _s3Client.DeleteObjectAsync(request).ConfigureAwait(false);

            if (response?.HttpStatusCode.Equals(System.Net.HttpStatusCode.NoContent) == true)

            {

                return (true, "File has been deleted successfully.");

            }

            return (false, "File no exists.");

        }

    }


    public interface IAwsS3

    {

        Task<(bool IsSuccess, string Result)> WriteFile(IFormFile file, string uploadPath);

        Task<(bool IsSuccess, Stream Result)> ReadFile(string keyName);

        Task<(bool IsSuccess, string Result)> DeleteFile(string keyName);

    }

}






Saturday 6 August 2022

  1. Create a new Windows Forms application.



  2. Create a database (named Sample). Add a table tbl_Record. The following is the table schema for creating tbl_Record.



  3. Create a form (named frmMain) and drop a Label, TextBox, Button and DataGridView control from the ToolBox.

     
Now, go to the frmMain.cs code and add the System.Data and System.Data.SqlClient namespaces.
 
frmMain.cs Code
  1. using System;  
  2. using System.Data;  
  3. using System.Windows.Forms;  
  4. using System.Data.SqlClient;  
  5.   
  6. namespace InsertUpdateDeleteDemo  
  7. {  
  8.     public partial class frmMain : Form  
  9.     {  
  10.         SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");  
  11.         SqlCommand cmd;  
  12.         SqlDataAdapter adapt;  
  13.         //ID variable used in Updating and Deleting Record  
  14.         int ID = 0;  
  15.         public frmMain()  
  16.         {  
  17.             InitializeComponent();  
  18.             DisplayData();  
  19.         }  
  20.         //Insert Data  
  21.         private void btn_Insert_Click(object sender, EventArgs e)  
  22.         {  
  23.             if (txt_Name.Text != "" && txt_State.Text != "")  
  24.             {  
  25.                 cmd = new SqlCommand("insert into tbl_Record(Name,State) values(@name,@state)", con);  
  26.                 con.Open();  
  27.                 cmd.Parameters.AddWithValue("@name", txt_Name.Text);  
  28.                 cmd.Parameters.AddWithValue("@state", txt_State.Text);  
  29.                 cmd.ExecuteNonQuery();  
  30.                 con.Close();  
  31.                 MessageBox.Show("Record Inserted Successfully");  
  32.                 DisplayData();  
  33.                 ClearData();  
  34.             }  
  35.             else  
  36.             {  
  37.                 MessageBox.Show("Please Provide Details!");  
  38.             }  
  39.         }  
  40.         //Display Data in DataGridView  
  41.         private void DisplayData()  
  42.         {  
  43.             con.Open();  
  44.             DataTable dt=new DataTable();  
  45.             adapt=new SqlDataAdapter("select * from tbl_Record",con);  
  46.             adapt.Fill(dt);  
  47.             dataGridView1.DataSource = dt;  
  48.             con.Close();  
  49.         }  
  50.         //Clear Data  
  51.         private void ClearData()  
  52.         {  
  53.             txt_Name.Text = "";  
  54.             txt_State.Text = "";  
  55.             ID = 0;  
  56.         }  
  57.         //dataGridView1 RowHeaderMouseClick Event  
  58.         private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)  
  59.         {  
  60.             ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());  
  61.             txt_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();  
  62.             txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();  
  63.         }  
  64.         //Update Record  
  65.         private void btn_Update_Click(object sender, EventArgs e)  
  66.         {  
  67.             if (txt_Name.Text != "" && txt_State.Text != "")  
  68.             {  
  69.                 cmd = new SqlCommand("update tbl_Record set Name=@name,State=@state where ID=@id", con);  
  70.                 con.Open();  
  71.                 cmd.Parameters.AddWithValue("@id", ID);  
  72.                 cmd.Parameters.AddWithValue("@name", txt_Name.Text);  
  73.                 cmd.Parameters.AddWithValue("@state", txt_State.Text);  
  74.                 cmd.ExecuteNonQuery();  
  75.                 MessageBox.Show("Record Updated Successfully");  
  76.                 con.Close();  
  77.                 DisplayData();  
  78.                 ClearData();  
  79.             }  
  80.             else  
  81.             {  
  82.                 MessageBox.Show("Please Select Record to Update");  
  83.             }  
  84.         }  
  85.         //Delete Record  
  86.         private void btn_Delete_Click(object sender, EventArgs e)  
  87.         {  
  88.             if(ID!=0)  
  89.             {  
  90.                 cmd = new SqlCommand("delete tbl_Record where ID=@id",con);  
  91.                 con.Open();  
  92.                 cmd.Parameters.AddWithValue("@id",ID);  
  93.                 cmd.ExecuteNonQuery();  
  94.                 con.Close();  
  95.                 MessageBox.Show("Record Deleted Successfully!");  
  96.                 DisplayData();  
  97.                 ClearData();  
  98.             }  
  99.             else  
  100.             {  
  101.                 MessageBox.Show("Please Select Record to Delete");  
  102.             }  
  103.         }  
  104.     }  
  105. }  
In the preceding code, I created a dataGridView1_RowHeaderMouseClick Event for updating and deleting the selected record. When the user clicks on the Row Header of a row then the data present in the cell of the row is stored into the TextBoxes. The DisplayData() method fills in the data in the DataGridView.
 
The Clear() method clears the data present in the TextBox as well as in the ID(int) variable.

Using extensions in Visual Studio Code

C#

Ctrl +Shit + p ( .NET :Generate Assests For build and debug)

Roslynator

.NET Core Test Explorer

C# Namespace Autocompletion

Auto-Using for C#

C# XML Documentation Comments

NuGet Reverse Package Search ("Add Package" support)

Code Spell Checker

vscode-icons

Path Intellisense

EditorConfig for VS Code

SQL Server (mssql)

GitHub Copilot

REST Client

GitLens — Git supercharged

VS Browser

Highlight Trailing White Spaces

jwt-decoder

Markdown All in One

Markdown Preview Enhanced

markdownlint

Docker

Vim


Wednesday 11 August 2021

How to use Captcha Code in your mvc project

1) how to check captcha in controller.(write this code to your controller function)

using Capcha.HtmlHelpers;

// Code for validating the CAPTCHA  

if (this.CheckCapcha()){ 

    *// do case of capcha is valid*

}

2) how to display captcha in view(write this code to your view)

using Capcha.HtmlHelpers;

  @using Capcha.HtmlHelpers; //import this library on top

  @Html.Captcha(4) // if you want to display capcha with 4 char. replace 4 to your appropriate number to display n length capcha.

  @Html.MathCaptcha()  // if you want to display capcha as maths formula like (7+1=?),(2+95=?),etc.



Note :-Click Here to Download Captcha dll.



Friday 13 September 2019

Multi language with resource file in asp net core 2.0 (API)

Step 1 : Create Resource folder
Step 2 : SharedResources.cs
namespace PillarCore.Api
{
    public class SharedResources
    {
    }
}
Step 3 : Create SharedResources.en-US.resx
<?xml version="1.0" encoding="utf-8"?>
<root>
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" use="required" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <data name="Msg-required" xml:space="preserve">
    <value>Api call done</value>
  </data>
   <data name="model-user-required" xml:space="preserve">
    <value>User Name is required.</value>
  </data>

</root>

Step 4 : create SharedResources.ja-JP.resx

<?xml version="1.0" encoding="utf-8"?>
<root>
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" use="required" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <data name="Msg-required" xml:space="preserve">
    <value>API呼び出し完了</value>
  </data>
   <data name="model-user-required" xml:space="preserve">
    <value>ユーザー名が必要です。</value>
  </data>

</root>
Step 5 : create ResourceKeys.cs
  public static class ResourceKeys
    {
     

        public const string modeluserrequired= "model-user-required";
        public const string Msg = "Msg-required";
    }
Step 6 : create ValidateModelStateAttribute.cs
namespace PillarCore.Api.Infrastructure
{
    #pragma warning disable
    public class ValidateModelStateAttribute : ActionFilterAttribute
    {
        private readonly IStringLocalizer _localizer;
        public ValidateModelStateAttribute(IStringLocalizer localizer)
        {
             _localizer = localizer;
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                string _message = string.Join(",", context.ModelState.Values
                                               .SelectMany(x => x.Errors)
                                               .Select(x => _localizer[x.ErrorMessage]).Distinct());
             
                                             
                context.Result = new ObjectResult(JsonResponse(1,_message));
            }
        }

        public JsonResponse JsonResponse(int StatusCode, string Message, object Data = null) => new JsonResponse {
            StatusCode = StatusCode, Message = Message, Data = Data ?? new object()
        };
    }
}
Step 7 : ExceptionAttributeFilter.cs //Custome error Exception

namespace PillarCore.Api.Infrastructure
{
    #pragma warning disable
    public class ExceptionAttributeFilter : ExceptionFilterAttribute
    {
        public override void OnException(ExceptionContext context)
        {
            var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            Common.SetLog(context?.Exception, (controllerActionDescriptor?.ActionName ?? ""));
            context.Result = new ObjectResult(JsonResponse(Status.Error, StatusMessage.Error));
            base.OnException(context);
        }
        public JsonResponse JsonResponse(int StatusCode, string Message, object Data = null) => new JsonResponse { StatusCode = StatusCode, Message = Message, Data = Data ?? new object() };
 
    }
}
Step 8 : create model class
public class UserModel
    {
        [Required(ErrorMessage = ResourceKeys.modeluserrequired)]
        public string user{ get; set; }
}
Step 9 : Login method in API
[AllowAnonymous]
        [HttpPost("LoginUser")]
        public async Task<JsonResponse> LoginUser([FromBody]UserModel value)
        {
return JsonResponse("success", _localizer[ResourceKeys.Msg].Value);
}
Step 10 : change in Startup file

  private const string defaultResourcePath = "Resources";///Resource folder
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            DefaultCulture = Configuration["Configuration:DefaultCulture"] ?? "ja-JP";///Resource defualt language set return Japanese you can set en-US means return English
        }
public void ConfigureServices(IServiceCollection services)
        {
RegisterLocalizationService(services);
  var supportedCultures = GetSupportedCultures();
  services.AddMvc(options =>
            {
                    options.Filters.Add(typeof(ValidateModelStateAttribute)); //Set Dynamic validation for invalied argument
                    options.Filters.Add(typeof(ExceptionAttributeFilter)); ///Set Custome error Exception

            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);//.AddJsonOptions(opt => opt.SerializerSettings.ContractResolver = new DefaultContractResolver());
            services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ReferenceLoopHandling =
                Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });
           
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {         
     
            var supportedCultures = GetSupportedCultures();
            app.UseRequestLocalization(new RequestLocalizationOptions()
            {
                DefaultRequestCulture = new RequestCulture(DefaultCulture),
                SupportedCultures = supportedCultures,
                SupportedUICultures = supportedCultures
            });
         
            app.UseMvc();
        }
  private void RegisterLocalizationService(IServiceCollection services)
        {
            services.AddLocalization(options => options.ResourcesPath = defaultResourcePath);
            var sharedResourceType = typeof(SharedResources);
            services.AddSingleton(x => x.GetService<IStringLocalizerFactory>().Create(sharedResourceType));
        }
        private List<CultureInfo> GetSupportedCultures() 
        {
            return new List<CultureInfo>
            {
               new CultureInfo(DefaultCulture)
            };
        }

SqlDataBaseLibrary

using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using AOS.Repository.Infrastructure; using S...