What is CRUD operation PART 7 With Example Code

These classes are designed to encapsulate various types of responses in a web application, providing a consistent structure for handling and returning responses from different parts of the application. They allow for clear communication of the operation status, associated data, and any relevant messages.




using System.Collections.Generic;

 

namespace WebApplication.Repository

{

    /// <summary>

    /// Represents the base response structure for API responses.

    /// </summary>

    public class BaseResponse

    {

        /// <summary>

        /// Initializes a new instance of the <see cref="BaseResponse"/> class.

        /// </summary>

        public BaseResponse()

        {

            this.Message = new List<string>();

        }

 

        /// <summary>

        /// Gets or sets a value indicating whether the operation was successful.

        /// </summary>

        public bool Success { get; set; }

 

        /// <summary>

        /// Gets or sets the total number of records.

        /// </summary>

        public int Total { get; set; }

 

        /// <summary>

        /// Gets or sets the page size.

        /// </summary>

        public int PageSize { get; set; }

 

        /// <summary>

        /// Gets or sets the page number.

        /// </summary>

        public int PageNumber { get; set; }

 

        /// <summary>

        /// Gets or sets the list of messages associated with the response.

        /// </summary>

        public IList<string> Message { get; set; }

    }

 

    /// <summary>

    /// Represents the response structure for API responses with data.

    /// </summary>

    /// <typeparam name="T">The type of data.</typeparam>

    public class Response<T> : BaseResponse

    {

        /// <summary>

        /// Gets or sets the data associated with the response.

        /// </summary>

        public virtual IList<T> Data { get; set; }

    }

 

    /// <summary>

    /// Represents the response structure for API responses indicating a missing title.

    /// </summary>

    public class MissingTitleResult : BaseResponse

    {

        /// <summary>

        /// Gets or sets the primary key ID.

        /// </summary>

        public long PKId { get; set; }

 

        /// <summary>

        /// Gets or sets the new primary key ID.

        /// </summary>

        public long NewPKId { get; set; }

    }

 

    /// <summary>

    /// Represents the response structure for API post requests.

    /// </summary>

    /// <typeparam name="T">The type of data.</typeparam>

    public class PostResponse<T> : BaseResponse

    {

        /// <summary>

        /// Gets or sets the data associated with the response.

        /// </summary>

        public virtual T Data { get; set; }

    }

 

    /// <summary>

    /// Represents a generic response structure for API responses.

    /// </summary>

    public class Response

    {

        /// <summary>

        /// Gets or sets a value indicating whether the operation was successful.

        /// </summary>

        public bool Success { get; set; }

 

        /// <summary>

        /// Gets or sets the message associated with the response.

        /// </summary>

        public string Message { get; set; }

 

        /// <summary>

        /// Gets or sets the primary key ID.

        /// </summary>

        public long PKId { get; set; }

    }

 

    /// <summary>

    /// Represents the response structure for API responses containing byte information.

    /// </summary>

    public class GetByteArray : BaseResponse

    {

        /// <summary>

        /// Gets or sets the byte information.

        /// </summary>

        public byte[] ByteInfo { get; set; }

    }

}

 




---------------------------

using System.Data;

using System.Data.SqlClient;

using System.Runtime.InteropServices;

 

namespace WebApplication.Repository

{

    /// <summary>

    /// Provides utility methods for database operations.

    /// </summary>

    public class ProjectUtility

    {

        /// <summary>

        /// Creates a new SqlParameter object with the specified parameter name, SQL type, and value.

        /// </summary>

        /// <param name="paramName">The name of the parameter.</param>

        /// <param name="type">The SQL type of the parameter.</param>

        /// <param name="value">The value of the parameter.</param>

        /// <returns>A new SqlParameter object.</returns>

        public static SqlParameter GetSQLParam(string paramName, SqlDbType type, dynamic value)

        {

            SqlParameter sqlParam = new SqlParameter(paramName, type);

            sqlParam.Value = value;

            return sqlParam;

        }

 

        /// <summary>

        /// Creates a new SqlParameter object with the specified parameter name, SQL type, value, and optional type name.

        /// </summary>

        /// <param name="paramName">The name of the parameter.</param>

        /// <param name="type">The SQL type of the parameter.</param>

        /// <param name="value">The value of the parameter.</param>

        /// <param name="typeName">The type name of the parameter (optional).</param>

        /// <returns>A new SqlParameter object.</returns>

        public static SqlParameter GetSQLParam(string paramName, SqlDbType type, dynamic value, [Optional] string typeName)

        {

            SqlParameter sqlParam = new SqlParameter(paramName, type);

            sqlParam.Value = value;

            if (typeName != null)

            {

                sqlParam.TypeName = typeName;

            }

            return sqlParam;

        }

 

        /// <summary>

        /// Generates a sort order string based on the specified sort by and sort direction.

        /// </summary>

        /// <param name="SortBy">The column to sort by.</param>

        /// <param name="SortDirection">The sort direction (ascending or descending).</param>

        /// <returns>The sort order string.</returns>

        public static string GetSortOrder(string SortBy, string SortDirection)

        {

            return SortBy + " " + (SortDirection.ToLower() == "descending" ? "DESC" : "");

        }

 

        /// <summary>

        /// Writes a message to the log file.

        /// </summary>

        /// <param name="msg">The message to write to the log file.</param>

        public static void WriteLogFile(string msg)

        {

            const string path = @"C:\Program Files\Log.txt";

            File.AppendAllText(path, msg);

        }

 

        /// <summary>

        /// Generates a random number between 100000 and 999999.

        /// </summary>

        /// <returns>The generated random number.</returns>

        public static int GenerateRandomNumber()

        {

            int _min = 100000;

            int _max = 999999;

            Random _rdm = new Random();

            return _rdm.Next(_min, _max);

        }

 

        /// <summary>

        /// Generates an array of SQL parameters.

        /// </summary>

        /// <param name="v1">Parameter 1.</param>

        /// <param name="varchar">Parameter 2.</param>

        /// <param name="v2">Parameter 3.</param>

        /// <returns>An array of SQL parameters.</returns>

        public static object[] GetSQLParam(string v1, object varchar, object v2)

        {

            throw new NotImplementedException();

        }

    }

}

 


-------------------------------


using System.Data.Common;

using System.Data.SqlClient;

using System.Data;

using System.Data.Entity;

 

namespace WebApplication.Repository

{

    /// <summary>

    /// Represents the database context for the project.

    /// </summary>

    public class ProjectContext : DbContext

    {

        private SqlConnection con;

 

        /// <summary>

        /// Initializes a new instance of the <see cref="ProjectContext"/> class.

        /// </summary>

        public ProjectContext()

        {

 

        }

 

        /// <summary>

        /// Gets the database connection associated with this context.

        /// </summary>

        public Database Db

        {

            get

            {

                var configuration = GetConfiguration();

                con = new SqlConnection(configuration.GetSection("Data").GetSection("ConnectionString").Value);

                Database.Connection.ConnectionString = con.ConnectionString;

                return Database;

            }

        }

 

        /// <summary>

        /// Retrieves the application configuration settings.

        /// </summary>

        /// <returns>The configuration root.</returns>

        public IConfigurationRoot GetConfiguration()

        {

            var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

            return builder.Build();

        }

 

        /// <summary>

        /// Overrides the base Set method to return a DbSet for the specified entity type.

        /// </summary>

        /// <typeparam name="TEntity">The type of the entity.</typeparam>

        /// <returns>A DbSet instance for the specified entity type.</returns>

        public new DbSet<TEntity> Set<TEntity>() where TEntity : class

        {

            return base.Set<TEntity>();

        }

 

        /// <summary>

        /// Executes a SQL query against the database and returns the result as a list of entities of type TEntity.

        /// </summary>

        /// <typeparam name="TEntity">The type of the entity.</typeparam>

        /// <param name="commandText">The SQL command text.</param>

        /// <param name="parameters">The parameters for the SQL query.</param>

        /// <returns>A list of entities of type TEntity.</returns>

        public IList<TEntity> QuerySQL<TEntity>(string commandText, params object[] parameters) where TEntity : class

        {

            if (parameters != null && parameters.Length > 0)

            {

                for (int i = 0; i <= parameters.Length - 1; i++)

                {

                    var p = parameters[i] as DbParameter;

                    if (p == null)

                    {

                        throw new Exception("Not support parameter type");

                    }

 

                    commandText += i == 0 ? " " : ", ";

 

                    commandText += "@" + p.ParameterName;

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

                    {

                        commandText += " output";

                    }

                }

            }

 

            return this.Database.SqlQuery<TEntity>(commandText, parameters).ToList();

        }

 

        /// <summary>

        /// Executes a SQL query against the database and returns the result as an enumerable collection of objects of type TElement.

        /// </summary>

        /// <typeparam name="TElement">The type of the elements in the result.</typeparam>

        /// <param name="commandText">The SQL command text.</param>

        /// <param name="parameters">The parameters for the SQL query.</param>

        /// <returns>An enumerable collection of objects of type TElement.</returns>

        public IEnumerable<TElement> ExecuteSQL<TElement>(string commandText, params object[] parameters)

        {

            if (parameters != null && parameters.Length > 0)

            {

                for (int i = 0; i <= parameters.Length - 1; i++)

                {

                    var p = parameters[i] as DbParameter;

                    if (p == null)

                    {

                        throw new Exception("Not support parameter type");

                    }

 

                    commandText += i == 0 ? " " : ", ";

 

                    commandText += "@" + p.ParameterName;

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

                    {

                        commandText += " output";

                    }

                }

            }

 

            return this.Database.SqlQuery<TElement>(commandText, parameters);

        }

    }

}