using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI.WebControls;

namespace GenClassLibrary
{
    public class GenClass : ValidateData
    {
        private string objCon;
        private SqlConnection Conn;
        private string strQuery;
        private DateTime? strreturndate = null;
        #region all_func
        public SqlConnection Connect()
        {
            try
            {
                objCon = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
                Conn = new SqlConnection(objCon);
                if (Conn.State == ConnectionState.Closed)
                {
                    Conn.Open();
                }
               

            }
            catch (Exception ex)
            {
                Conn = null;

            }
            return Conn;
        }
        public int GetLineNumber(Exception ex)
        {
            var lineNumber = 0;
            const string lineSearch = ":line ";
            var index = ex.StackTrace.LastIndexOf(lineSearch);
            if (index != -1)
            {
                var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
                if (int.TryParse(lineNumberText, out lineNumber))
                {
                }
            }
            return lineNumber;
        }
        public DataTable Returndata(string query, SqlConnection conn)
        {

            DataTable dt = new DataTable();
            SqlCommand com = new SqlCommand(query, conn);
            SqlDataAdapter ada = new SqlDataAdapter(com);
            ada.Fill(dt);
            com.Dispose();
            return dt;

        }
        public void Filldropdown(string query, DropDownList ddlCategory)
        {
            SqlConnection con = Connect();
            DataTable dt = new DataTable();
            try
            {
                dt = Returndata(query, con);
                ddlCategory.DataSource = dt;
                ddlCategory.DataTextField = dt.Columns[0].ToString();
                ddlCategory.DataValueField = dt.Columns[1].ToString();
                ddlCategory.DataBind();
                ListItem liSelect = new ListItem("[Select]", "0");
                ddlCategory.Items.Insert(0, liSelect);
            }
            catch (Exception ex)
            {

            }
            finally
            {
                con.Close();
                dt.Clear();
                dt.Dispose();
            }
        }
        public int chkDuplicateID(string tblnm, string colnm, string cond)
        {
            try
            {
                SqlConnection con = Connect();
                string str = "select " + colnm + " from " + tblnm + " where " + colnm + " = @cond";

                SqlDataReader dr = null;
                SqlCommand com = new SqlCommand(str, con);
                com.Parameters.Add(new SqlParameter("@cond", cond));
                dr = com.ExecuteReader();

                if (dr.Read())
                {
                    con.Close();
                    return 0;
                }
                else
                {
                    con.Close();
                    return 1;
                }
            }
            catch
            {
                return -1;
            }

        }
        public int chkDuplicateID(string tblnm, string colnm, string cond, string colnm1, string cond1)
        {
            SqlConnection con = Connect();
            string str = "select " + colnm + " from " + tblnm + " where " + colnm + " = @cond and " + colnm1 + " = @cond1";

            SqlDataReader dr = null;
            SqlCommand com = new SqlCommand(str, con);
            com.Parameters.Add(new SqlParameter("@cond", cond));
            com.Parameters.Add(new SqlParameter("@cond1", cond));
            dr = com.ExecuteReader();

            if (dr.Read())
            {
                con.Close();
                return 0;
            }
            else
            {
                con.Close();
                return 1;
            }

        }
        public int chkDuplicateID1(string tblnm, string colnm, string cond, string cond2)
        {
            SqlConnection con = Connect();
            string str = "select " + colnm + " from " + tblnm + " where " + colnm + " = @cond and " + cond2 + "";

            SqlDataReader dr = null;
            SqlCommand com = new SqlCommand(str, con);
            com.Parameters.Add(new SqlParameter("@cond", cond));
            dr = com.ExecuteReader();

            if (dr.Read())
            {
                con.Close();
                return 0;
            }
            else
            {
                con.Close();
                return 1;
            }

        }
        public string encode(string code)
        {
            string UsernameEncoded = null;
            try
            {
                if (code != "")
                {

                    string Username = null;
                    Username = code.ToString();

                    // first, for rudimentary encryption, let's Base64 encode this value
                    byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(Username);
                    string strreturndate = null;
                    strreturndate = Convert.ToBase64String(data);

                    // second, to ensure a valid QueryString value, we need to UrlEncode this value

                    UsernameEncoded = HttpUtility.UrlEncode(strreturndate);
                }

            }
            catch (Exception ex)
            {

            }
            return UsernameEncoded;
        }
        public string decode(string code)
        {
            string Username = null;
            try
            {
                if (code != "")
                {

                    string UsernameEncoded = null;
                    UsernameEncoded = code;

                    // we need to "decode" the username from UrlEncoding
                    string UsernameBase64 = null;
                    UsernameBase64 = HttpUtility.UrlDecode(UsernameEncoded);

                    // now, we need to undo the Base64 encoding

                    byte[] data = Convert.FromBase64String(UsernameBase64);
                    Username = System.Text.ASCIIEncoding.ASCII.GetString(data);
                }

            }
            catch (Exception ex)
            {

            }
            return Username;
        }
        public void sessionreset(string opt)
        {
            try
            {
                HttpContext.Current.Session.Clear();
                HttpContext.Current.Session.Abandon();
                HttpContext.Current.Response.Cookies.Add(new HttpCookie("InterMark", ""));
                HttpContext.Current.Response.Cookies["InterMark"].HttpOnly = true;
                HttpContext.Current.Response.Cookies.Remove("InterMark");
                HttpContext.Current.Response.Redirect("~/Contents/logout.aspx?opt=" + opt.Trim(), false);
            }
            catch (Exception ex)
            {

            }
        }
        public void sessionreset()
        {
            try
            {
                HttpContext.Current.Session.Clear();
                HttpContext.Current.Session.Abandon();
                HttpContext.Current.Response.Cookies.Add(new HttpCookie("InterMark", ""));
                HttpContext.Current.Response.Cookies["InterMark"].HttpOnly = true;
                HttpContext.Current.Response.Cookies.Remove("InterMark");
                HttpContext.Current.Response.Redirect("~/Contents/logout.aspx", false);
            }
            catch (Exception ex)
            {

            }
        }
        public DateTime dateformat(string Date_to_convert)
        {
            try
            {
                if (Date_to_convert != "")
                {
                    DateTime date1 = DateTime.ParseExact(Date_to_convert, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture,
                    System.Globalization.DateTimeStyles.None);
                    strreturndate = Convert.ToDateTime(date1.ToString());
                }
            }
            catch (Exception ex)
            {

            }
            return Convert.ToDateTime(strreturndate);
        }
        public void SetSessionCookie()
        {
            // SET SESSION COOKIE ON PAGE LOAD
            try
            {
                System.Web.Security.FormsAuthenticationTicket AuthTicketPage = null;
                AuthTicketPage = new System.Web.Security.FormsAuthenticationTicket(1, "InterMark", DateTime.Now, DateTime.Now.AddMinutes(10), false, "");
                string PageTicket = System.Web.Security.FormsAuthentication.Encrypt(AuthTicketPage);
                //HttpContext.Current.Response.Cookies.Add(new HttpCookie("AuthTokenPage", PageTicket));
                HttpContext.Current.Session["AuthTokenPage"] = PageTicket;
            }
            catch (Exception Ex)
            {

            }
        }
        public void createdir(string path)
        {
            try
            {
                if (!validateEmptyString(path))
                {
                    if (Directory.Exists(path))
                        return;
                    else
                    {

                        // if not created then it will create it.
                        Directory.CreateDirectory(path);
                        return;
                    }
                }
            }
            catch (DirectoryNotFoundException ex)
            {

            }
            catch (Exception ex)
            {

            }
        }
        public string fileupload(FileUpload uploadfile, string userid, string extensionname)
        {
            string destdir, filename, fileextension, destpath, dbfilePath = null;
            DateTime time = DateTime.Now;
            string format1 = "dd.MM.yyyy_HH.mm.ss_fff_tt";
            string savefilename = null;
            try
            {
                destdir = HttpContext.Current.Server.MapPath("~/UploadFile/" + userid.ToString() + "");
                filename = System.IO.Path.GetFileName(uploadfile.PostedFile.FileName).Replace(" ", "");
                fileextension = System.IO.Path.GetExtension(uploadfile.PostedFile.FileName);
                filename = extensionname.ToString() + time.ToString(format1) + filename;
                destpath = System.IO.Path.Combine(destdir, filename);
                uploadfile.PostedFile.SaveAs(destpath);
                dbfilePath = "~/UploadFile/" + userid.ToString() + "/" + filename;
                savefilename = filename.ToString();
            }
            catch (DirectoryNotFoundException ex)
            {

            }
            catch (Exception ex)
            {

            }
            return savefilename;
        }
        public bool VALIDIMAGE_TYPE(FileUpload f1)
        {
            try
            {
                System.IO.BinaryReader r = new System.IO.BinaryReader(f1.PostedFile.InputStream);
                string fileclass = "";
                byte buffer;
                buffer = r.ReadByte();
                fileclass = buffer.ToString();
                buffer = r.ReadByte();
                fileclass += buffer.ToString();

                if (fileclass == "7173" || fileclass == "255216" || fileclass == "6677" || fileclass == "13780" || fileclass == "255224")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (DirectoryNotFoundException ex)
            {

            }
            catch (Exception ex)
            {

            }

            return false;
        }
        #endregion
        #region Parmeterised Query
        public void bindgrid_byParam(SqlCommand cmd, GridView grid)
        {
            SqlConnection con = Connect();
            DataSet ds = new DataSet();
            SqlDataAdapter sda = new SqlDataAdapter();
            try
            {
                cmd.CommandType = CommandType.Text;
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                sda.Fill(ds);
                grid.DataSource = ds;
                grid.DataBind();
                ds.Clear();
                ds.Dispose();

            }
            catch (Exception ex)
            {

            }
            finally
            {
                con.Close();
                cmd.Dispose();
                ds = null;
                sda.Dispose();
            }
        }
        public DataTable GetData_byParam(SqlCommand cmd, SqlConnection con)
        {
            DataTable dt = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            try
            {
                sda.SelectCommand = cmd;
                sda.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {

                return null;
            }
            finally
            {
                sda.Dispose();
            }
        }
        public DataTable GetData_byParam_pr(SqlCommand cmd, SqlConnection con)
        {
            DataTable dt = new DataTable();
            SqlDataAdapter sda = new SqlDataAdapter();
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = con;
            try
            {
                sda.SelectCommand = cmd;
                sda.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {

                return null;
            }
            finally
            {
                sda.Dispose();
            }
        }


        public void executecommand_byParam(SqlCommand cmd, SqlConnection con)
        {
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            try
            {
                cmd.ExecuteNonQuery();

            }
            catch (Exception ex)
            {


            }
        }
        public void Filldropdown(SqlCommand cmd, DropDownList ddlCategory)
        {
            SqlConnection con = Connect();
            DataSet ds = new DataSet();
            SqlDataAdapter sda = new SqlDataAdapter();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            try
            {

                sda.SelectCommand = cmd;
                sda.Fill(ds);
                ddlCategory.DataSource = ds;
                ddlCategory.DataTextField = ds.Tables[0].Columns[0].ToString();
                ddlCategory.DataValueField = ds.Tables[0].Columns[1].ToString();
                ddlCategory.DataBind();
                ListItem liSelect = new ListItem("[Select]", "0");
                ddlCategory.Items.Insert(0, liSelect);
            }
            catch (Exception ex)
            {

            }
            finally
            {
                ds.Clear();
                ds.Dispose();
                sda.Dispose();
            }
        }
        public void TempActivityDelete(string uid, string time)
        {//log entry when successful logout and browser closed
            Conn = Connect();
            try
            {
                SqlCommand cmd = new SqlCommand("sp_adm_logintrans", Conn);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.Add("@int_userid", SqlDbType.Int).Value = uid;
                cmd.Parameters.Add("@vchr_loginstarttime", SqlDbType.DateTime).Value = time;
                cmd.Parameters.Add("@vchr_logouttime", SqlDbType.DateTime).Value = DateTime.Now;
                cmd.Parameters.Add("@vchr_logouttype", SqlDbType.VarChar, 100).Value = "BROWSERCLOSED";
                cmd.Parameters.Add("@action", SqlDbType.VarChar, 100).Value = "logout";
                cmd.Parameters.Add("@Flag", SqlDbType.Int);
                cmd.Parameters["@Flag"].Direction = ParameterDirection.Output;
                cmd.ExecuteNonQuery();
                int res = (int)cmd.Parameters["@Flag"].Value;
                // FOR HAVING SUCCESSFULLY INSERTED DATA

            }
            catch (Exception ex)
            {

            }
            finally
            {
                Conn.Close();
                Conn.Dispose();
            }
        }
        #endregion

        public static bool IsSessionExpired()
        {
            if (HttpContext.Current.Session != null)
            {
                if (HttpContext.Current.Session.IsNewSession)
                {
                    string CookieHeaders = HttpContext.Current.Request.Headers["Cookie"];

                    if ((null != CookieHeaders) && (CookieHeaders.IndexOf("ASP.NET_SessionId") >= 0))
                    {
                        // IsNewSession is true, but session cookie exists,
                        // so, ASP.NET session is expired
                        return true;
                    }
                }
            }

            // Session is not expired and function will return false,
            // could be new session, or existing active session
            return false;
        }

        #region Send Email

        public string getEmailId()
        {
            string emialids = "";
            // Establish the connection object.
            SqlConnection mySqlConnection;

            // Open the connection.
            mySqlConnection = Connect();

            try
            {
                // Establish data objects.
                SqlCommand mySqlCommand;
                DataSet myDataSet = new DataSet();

                // Create a new SQL Command and give it the name of the stored procedure and the SQL connection.
                mySqlCommand = new System.Data.SqlClient.SqlCommand("sp_setup_selectsystemparameter", mySqlConnection);

                // Inform the command that it is a stored procedure.
                mySqlCommand.CommandType = CommandType.StoredProcedure;

                // We now add any available parameters to the command.


                // Else add the parameters!
                mySqlCommand.Parameters.Add("@ParameterName", SqlDbType.VarChar, 50).Value = "AdminEmail";


                //Establish the DataAdapter
                SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(mySqlCommand);
                DataTable myDataTable = new DataTable();

                //Fill the DataTable through SqlDataAdapter
                mySqlDataAdapter.Fill(myDataTable);

                //Bind the Datasource to string with comma
                for (int i = 1; i < myDataTable.Rows.Count; i++)
                {
                    emialids += myDataTable.Rows[i][0].ToString() + ",";
                }
                emialids = emialids.TrimEnd(',');

                mySqlCommand.Dispose();

            }

            catch (Exception outerEx)
            {
                throw new Exception(outerEx.Message + " Possibly due to failed database read.");
            }
            finally
            {
                // The connection close must be in the finally block so that an error
                // will not leave it open.

                // Close the Connection.
                mySqlConnection.Close();

            }
            return emialids;
        }


        public bool SendMail(string to, string cc, string subject, string messageBody)
        {
            try
            {
                SmtpClient smtpClient = new SmtpClient();
                MailMessage message = new MailMessage();

                string sHost = System.Configuration.ConfigurationManager.AppSettings["Host"];
                bool sEnableSsl = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["EnableSsl"]);
                string sUserName = System.Configuration.ConfigurationManager.AppSettings["UserName"];
                string sPassword = System.Configuration.ConfigurationManager.AppSettings["Password"];
                int sPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Port"]);

                MailAddress fromAddress = new MailAddress(sUserName, "Intermark");
                smtpClient.Host = sHost;
                smtpClient.Port = sPort;
                smtpClient.EnableSsl = sEnableSsl;
                smtpClient.Credentials = new System.Net.NetworkCredential(sUserName, sPassword);
                message.From = fromAddress;


                string[] multiEmailid = to.Split(',');
                foreach (string emailid in multiEmailid)
                {
                    message.To.Add(new MailAddress(emailid));
                }
                message.Subject = subject;
                message.IsBodyHtml = true;
                message.Body = messageBody;
                message.Body += "<Br/><br/>Thanks <br/> Admin, Intermark.";
                smtpClient.Send(message);

                return true;
            }
            catch (Exception ex)
            {

                return false;
            }
        }


        #endregion
    }
}

