Translate

C# SQL Connection Best Connection Practice

Sunday, January 17, 2016 0


namespace Repository
{
    public class SQLRepository
    {

        DbConnector dbCon = new DbConnector();

        #region Query Execute
        public Result ExecuteQuery(string SQL)
        {
            Result oResult = new Result();
            SqlCommand oCmd = null;

            try
            {

                if (dbCon.Connect != null)
                {
                    dbCon.OpenConnection();
                    oCmd = new SqlCommand(SQL, dbCon.Connect);
                    oCmd.ExecuteNonQuery();
                    oResult.ResultState = true;
                }
            }
            catch (Exception ex)
            {
                oResult.ResultState = false;
                oResult.SqlError = ex.Message;
            }
            finally
            {
                dbCon.CloseConnection();
            }
            return oResult;
        }

        public Result ExecuteQuery(List SQL)
        {
            Result oResult = new Result();
            SqlTransaction oTransaction = null;
            SqlCommand oCmd = null;

            try
            {

                if (dbCon.Connect != null)
                {
                    dbCon.OpenConnection();
                    oTransaction = dbCon.Connect.BeginTransaction();
                    foreach (string s in SQL)
                    {
                        oCmd = new SqlCommand(s, dbCon.Connect);
                        oCmd.Transaction = oTransaction;
                        oCmd.ExecuteNonQuery();
                        oResult.ResultState = true;
                    }
                    oTransaction.Commit();
                }
            }
            catch (Exception ex)
            {
                oResult.ResultState = false;
                oResult.SqlError = ex.Message;
                if (oTransaction != null)
                    oTransaction.Rollback();
            }
            finally
            {
                dbCon.CloseConnection();
            }
            return oResult;
        }

        public Result ExecuteQueryParam(List SQL)
        {
            Result oResult = new Result();
            SqlTransaction oTransaction = null;
            SqlCommand oCmd = null;

            try
            {

                if (dbCon.Connect != null)
                {
                    dbCon.OpenConnection();
                    oTransaction = dbCon.Connect.BeginTransaction();
                    foreach (SQLQuery s in SQL)
                    {
                        oCmd = new SqlCommand(s.sql, dbCon.Connect);
                        oCmd.Transaction = oTransaction;

                        foreach (SQLParam param in s.Param)
                        {
                            SqlParameter picparameter = new SqlParameter();
                            picparameter.SqlDbType = param.DbType; //SqlDbType.Image;
                            picparameter.ParameterName = param.ParamName; //"@PIC";
                            picparameter.Value = param.ParamValue;
                            oCmd.Parameters.Add(picparameter);
                        }

                        oCmd.ExecuteNonQuery();
                        oResult.ResultState = true;
                    }
                    oTransaction.Commit();
                }
            }
            catch (Exception ex)
            {
                oResult.ResultState = false;
                oResult.SqlError = ex.Message;
                if (oTransaction != null)
                    oTransaction.Rollback();
            }
            finally
            {
                dbCon.CloseConnection();
            }
            return oResult;
        }

        #endregion

        public Result Select(string SQL)
        {
            Result oResult = new Result();
            SqlCommand oCmd = null;
            try
            {

                if (dbCon.Connect != null)
                {
                    oCmd = new SqlCommand(SQL, dbCon.Connect);
                    oCmd.CommandTimeout = 0;
                    SqlDataAdapter adapter = new SqlDataAdapter(oCmd);
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);
                    oResult.ResultState = true;
                    oResult.Data = dt;
                }
            }
            catch (Exception ex)
            {
                oResult.ResultState = false;
                oResult.SqlError = ex.Message;
            }
            finally
            {
                dbCon.CloseConnection();
            }
            return oResult;
        }

    }

    public class DbConnector
    {

        private SqlConnection connection;

        public DbConnector()
        {
            connection = new SqlConnection(GlobalConnection());
        }

        public string GlobalConnection()
        {

            //string entityConnectionString = ConfigurationManager.ConnectionStrings["ERPEntities"].ConnectionString;
            //string providerConnectionString = new EntityConnectionStringBuilder(entityConnectionString).ProviderConnectionString;
            //return providerConnectionString;

            string str = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
            //ConfigurationSettings.AppSettings["CNN"];
            return str;
        }

        public SqlConnection Connect
        {
            get { return connection; }
        }

        public ConnectionState OpenConnection()
        {
            Connect.Open();
            return ConnectionState.Open;
        }

        public ConnectionState CloseConnection()
        {
            Connect.Close();
            return ConnectionState.Closed;
        }
    }

    public class SQLQuery
    {
        public string sql { get; set; }
        public List Param = new List();
    }

    public class SQLParam
    {
        public string ParamName { get; set; }
        public byte[] ParamValue { get; set; }
        public SqlDbType DbType { get; set; }
    }

    //public class Result
    //{
    //    public bool ResultState;
    //    public string SqlError;
    //    public DataTable Data;
    //}

}


ASP.NET Page Close Confirmation

Friday, October 23, 2015 Category : 0

triggering closing X browser event

 

 

 <html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>


    <script type="text/javascript">
        function OnBeforeUnLoadPage() {
            if (document.getElementById('hdnRefresh').value == "") {
                var result = confirm('Are you sure you want to navigate?');
                if (result) {
                    UnLoadPage();
                }
                else {
                    return false;
                }
            }
        }
        function DetectRefreshKey() {
            if (event.keyCode == 116) {
                document.getElementById('hdnRefresh').value = "1";
            }
        }
        function UnLoadPage() {
            PageMethods.ClearSession();
        }
        function DetachBodyUnload() {
            document.body.onbeforeunload = null;
            document.body.onunload = null;
        }
    </script>



</head>
<body onbeforeunload="return OnBeforeUnLoadPage(); " onkeypress="DetectRefreshKey();">
    <form id="form1" runat="server">
    <input type="hidden" id="hdnRefresh" />
    <asp:ScriptManager ID="sc" runat="server" EnablePageMethods="true" EnablePartialRendering="true">
    </asp:ScriptManager>
    <asp:Button ID="btnTest" runat="server" Text="Refresh" OnClientClick="DetachBodyUnload();"
        OnClick="btnTest_Click" />
    </form>
</body>

</html>




code behind:

protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext.Current.Session["test"] = "TEST DATA";
        }
        [WebMethod]
        public static void ClearSession()
        {
            HttpContext.Current.Session.Remove("test");
        }
        protected void btnTest_Click(object sender, EventArgs e)
        {           
        }





http://forums.asp.net/t/1580541.aspx

SQL SERVER – Attach mdf file without ldf file in Database

Tuesday, October 13, 2015 Category : 2


USE [master]
GO
-- Method 1: I use this method
EXEC sp_attach_single_file_db @dbname='TestDb',
@physname=N'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDb.mdf'
GO



-- Method 2:

CREATE DATABASE TestDb ON
(FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDb.mdf')
FOR ATTACH_REBUILD_LOG
GO


-- Method 3:
CREATE DATABASE TestDb ON
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\TestDb.mdf')
FOR ATTACH
GO 




 Source : http://blog.sqlauthority.com/2010/04/26/sql-server-attach-mdf-file-without-ldf-file-in-database/



Exception case when fail to attach database and get such error like



"The log cannot be rebuilt because there were open transactions/users when the database was shutdown, no checkpoint occurred to the database, or the database was read-only. This error could occur if the transaction log file was manually deleted or lost due to a hardware or environment failure."  





Attaching the Damaged SQL Server Database

USE [master]
GO

CREATE DATABASE [TestDB_Repair]
 CONTAINMENT = NONE
 ON  PRIMARY
( NAME = N'TestDB_Repair_file1',
   FILENAME = N'E:\MSSQL\TestDB_Repair_1.mdf',
   SIZE = 8MB ,
   MAXSIZE = UNLIMITED,
   FILEGROWTH = 64MB)
 LOG ON
( NAME = N'TestDB_Repair_log_file1',
    FILENAME = N'E:\MSSQL\TestDB_Repair_1.ldf',
    SIZE = 8MB,
    MAXSIZE = 2048GB,
    FILEGROWTH = 32MB)


 Now we set the database offline.


USE master
GO

ALTER DATABASE [TestDB_Repair] SET OFFLINE WITH ROLLBACK IMMEDIATE
GO

At this point we can change the file location of our new database to point to our orphaned mdf file and set the location of the log file to a non-existent file.



USE master
GO

ALTER DATABASE [TestDB_Repair] MODIFY FILE(NAME='TestDB_Repair_file1', FILENAME= 'E:\MSSQL\TestDBCopy.mdf')
ALTER DATABASE [TestDB_Repair] MODIFY FILE(NAME='TestDB_Repair_log_file1', FILENAME= 'E:\MSSQL\TestDBCopy.ldf')
GO

Let’s bring the database back online.



USE master
GO

ALTER DATABASE [TestDB_Repair] SET ONLINE
GO





 

 

Rebuilding the SQL Server Transaction Log

USE master
GO

DBCC TRACEON(3604)
GO

ALTER DATABASE TestDB_Repair SET EMERGENCY
GO

ALTER DATABASE TestDB_Repair SET SINGLE_USER
GO

DBCC CHECKDB('TestDB_Repair', REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS
GO

ALTER DATABASE TestDB_Repair SET MULTI_USER
GO

 

Source : https://www.mssqltips.com/sqlservertip/3579/how-to-attach-a-sql-server-database-without-a-transaction-log-and-with-open-transactions/



ASP.NET authorize base class AuthorizeAttribute overload example

Tuesday, September 1, 2015 Category : 0

 public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        public string UsersConfigKey { get; set; }
        public string RolesConfigKey { get; set; }

        protected virtual CustomPrincipal CurrentUser
        {
            get { return HttpContext.Current.User as CustomPrincipal; }
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated)
            {
                var authorizedUsers = ConfigurationManager.AppSettings[UsersConfigKey];
                var authorizedRoles = ConfigurationManager.AppSettings[RolesConfigKey];

                Users = String.IsNullOrEmpty(Users) ? authorizedUsers : Users;
                Roles = String.IsNullOrEmpty(Roles) ? authorizedRoles : Roles;

                if (!String.IsNullOrEmpty(Roles))
                {
                    if (!CurrentUser.IsInRole(Roles))
                    {
                        filterContext.Result = new RedirectToRouteResult(new
                        RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));

                         base.OnAuthorization(filterContext); returns to login url
                    }
                }

                if (!String.IsNullOrEmpty(Users))
                {
                    if (!Users.Contains(CurrentUser.UserId.ToString()))
                    {
                        filterContext.Result = new RedirectToRouteResult(new
                        RouteValueDictionary(new { controller = "Error", action = "AccessDenied" }));

                         base.OnAuthorization(filterContext); returns to login url
                    }
                }
            }

        }

ASP.NET GridView Sorting

Saturday, March 21, 2015 Category : 0

Process 1 : 
 protected void gvUser_Sorting(object sender, GridViewSortEventArgs e)
        {

            string search = txtSearch.Text.Trim();
            string SortExp = e.SortExpression;
           
           
            List<Common.TblUser> oList = UserBLL.GetUserList();
            if (txtSearch.Text != "")
            {
                string text = txtSearch.Text.ToUpper();
                oList = oList.FindAll(m => m.FullName.ToUpper().Contains(text) || m.RoleName.ToUpper().Contains(text) || m.UserName.ToUpper().Contains(text) || m.ExternalID.ToUpper().Contains(text)).ToList();
            }

            System.Reflection.PropertyInfo property = oList.GetType().GetGenericArguments()[0].GetProperty(SortExp);
            if (e.SortDirection == SortDirection.Ascending)
            {
                oList = oList.OrderBy(g => property.GetValue(g, null)).ToList<Common.TblUser>();
            }
            else
            {
              oList =  oList.OrderByDescending(g => property.GetValue(g, null)).ToList<Common.TblUser>();
            }

            this.gvUser.DataSource = oList;
            this.gvUser.DataBind();

        }

Process 2
Using Object Datasource


  <asp:GridView ID="GVUserList" runat="server" AutoGenerateColumns="False"
                        DataSourceID="odsGrid" AllowPaging="True" AllowSorting="True"
 DataKeyNames="CBTID" >
                        <Columns>
                            <asp:BoundField DataField="BTName" HeaderText="BTName" SortExpression="BTName" />
                        </Columns>
                        <EmptyDataTemplate>
                            <table style="width:100%;">
                                <tr>
                                    <th>No Record Added</th>
                                </tr>
                            </table>
                        </EmptyDataTemplate>
                    </asp:GridView>


<asp:ObjectDataSource ID="odsGrid" runat="server" OldValuesParameterFormatString="original_{0}"
                        SelectMethod="SelectAllForGrid" TypeName="WellFood.Business.Managers.BrandTypeManager"
                        SortParameterName="Sortby">
                        <SelectParameters>
                            <asp:Parameter Name="SearchExpression" Type="String" />
                        </SelectParameters>
                    </asp:ObjectDataSource>





[DataObjectMethod(DataObjectMethodType.Select)]
        public List<BrandType> SelectAllForGrid(string SearchExpression, string Sortby)
        {
            if (string.IsNullOrEmpty(Sortby))
                Sortby = "PrdID";

            Query = @"SELECT ROW_NUMBER() OVER(ORDER BY   " + Sortby + @" ) as RowNum,
                    CBTID ,BTID ,BTName ,PrdID ,
                    PrdName ,GroupID ,GroupName ,FloorID ,VATPrcnt ,DiscPrcnt
                    FROM [BrandType]
                    order by RowNum";
            oR = sQLDal.Select(Query);
            List<BrandType> oList = new List<BrandType>();
            if (oR.ResultState && oR.Data.Rows.Count > 0)
            {
                oList = DataTableToClass.DataTableToList<BrandType>(oR.Data);
                return oList;
            }
            else return null;
        }

Entity Framework Connection Use As SqlConnection

Thursday, November 13, 2014 Category : , 0

        public static string GetConnectionString()
        {
            string entityConnectionString = ConfigurationManager.ConnectionStrings["ERPEntities"].ConnectionString;
            string providerConnectionString = new EntityConnectionStringBuilder(entityConnectionString).ProviderConnectionString;
            return providerConnectionString;
        }

C# DataTable to List Convert

Wednesday, November 12, 2014 Category : , 0


public static List DataTableToList(this DataTable table) where T : class, new()

        {
           try
            {
                List list = new List();
                foreach (var row in table.AsEnumerable())
               {
                    T obj = new T();
                    foreach (var prop in obj.GetType().GetProperties())
                    {
                        try
                        {
                            PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);

                            propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);

                        }
                        catch
                        {
                            continue;
                        }
                    }
                    list.Add(obj);
                }
                return list;
            }
            catch
            {
                return null;
            }
        }

Powered by Blogger.