using Dapper;
using Microsoft.AspNetCore.Http.Features;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using WK_KLI_LAPS_Service.Models;
using WK_KLI_LAPS_Service.Models.Configuration;
using WK_KLI_LAPS_Service.Models.Master;

namespace WK_KLI_LAPS_Service.App_Data
{
    public class CommonRepository
    {
        useractivitylogModel userlogmodel;

        public IEnumerable<servermasterModel> getServerInfo()
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spservermasterselect";
                param.Add("servermasterid_p", dbType: DbType.Int32, value: null, direction: ParameterDirection.Input);
                return dbConnection.Query<servermasterModel>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        //get the list of available action list
        public IEnumerable<object> getActionList()
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spgetactionlist";
                return dbConnection.Query<object>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        public string connectlinux()
        {
            string fileName = @"/efs/connectlinux.txt";

            try
            {
                // Check if file already exists. If yes, delete it.     
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
                bool isWindows = System.Runtime.InteropServices.RuntimeInformation
                                               .IsOSPlatform(OSPlatform.Windows);
                // Create a new file     
                using (FileStream fs = File.Create(fileName))
                {
                    // Add some text to file    
                    Byte[] title = new UTF8Encoding(true).GetBytes("Log file");
                    fs.Write(title, 0, title.Length);
                    byte[] author = new UTF8Encoding(true).GetBytes("From KLI");
                    fs.Write(author, 0, author.Length);
                }

                // Open the stream and read it back.    
                using (StreamReader sr = File.OpenText(fileName))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        Console.WriteLine(s);
                    }
                }
            }
            catch (Exception Ex)
            {
                ErrorLog(Ex);
                Console.WriteLine(Ex.ToString());
            }
            return fileName;
        }

        public string getfilesavelocation(int id)
        {
            try
            {
                bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                if (isWindows)
                {
                    IEnumerable<servermasterModel> sm = getServerInfo1(id, "Windows").ToList();
                    string root_path = sm.First().serverpath.ToString();
                    return root_path;
                }
                else
                {
                    IEnumerable<servermasterModel> sm = getServerInfo1(id, "Linux").ToList();
                    string root_path = sm.First().serverpath.ToString();
                    return root_path;
                }
            }
            catch (Exception ex)
            {
                ErrorLog(ex);
            }
            return "";
        }
        public IEnumerable<servermasterModel> getServerInfo1(int id, string ostype)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();

                const string query = @"public.spusrserverpathinfo";
                param.Add("p_tranid", dbType: DbType.Int32, value: id, direction: ParameterDirection.Input);
                param.Add("p_ostype", dbType: DbType.String, value: ostype, direction: ParameterDirection.Input);
                param.Add("p_lotid", dbType: DbType.Int32, value: null, direction: ParameterDirection.Input);
                param.Add("p_option", dbType: DbType.String, value: "serverinfo_job_tranid", direction: ParameterDirection.Input);
                return dbConnection.Query<servermasterModel>(query, param, commandType: CommandType.StoredProcedure);

            }
        }
        //public string sendnotificationmail(mailconfigModel maildetails, string fielddetails, string type, int typedetailid, string guid, string status)
        //{
        //    string emailhost = Startup.Configuration.GetValue<string>("AppSettings:emailhost");
        //    string emailusername = Startup.Configuration.GetValue<string>("AppSettings:emailusername");
        //    string emailpassword = Startup.Configuration.GetValue<string>("AppSettings:emailpassword");
        //    string documentlink = Startup.Configuration.GetValue<string>("AppSettings:documentlink");
        //    string requestlink = Startup.Configuration.GetValue<string>("AppSettings:requestlink");
        //    string documentlinkname = Startup.Configuration.GetValue<string>("AppSettings:documentlinkname");
        //    string requestlinkname = Startup.Configuration.GetValue<string>("AppSettings:requestlinkname");
        //    string emailportid = Startup.Configuration.GetValue<string>("AppSettings:emailportid");
        //    string servicelink = Startup.Configuration.GetValue<string>("AppSettings:servicelink");


        //    SmtpClient client = new SmtpClient();
        //    client.UseDefaultCredentials = false;
        //    client.Host = emailhost;
        //    client.EnableSsl = true;
        //    client.Port = Convert.ToInt32(emailportid);
        //    System.Net.NetworkCredential myCredential = new System.Net.NetworkCredential(emailusername, emailpassword);
        //    client.Credentials = myCredential;

        //    string s = "Invalid";
        //    StringBuilder sbody = new StringBuilder();


        //    sbody = getmailcontentformated(maildetails.mailcontent, fielddetails);


        //    MailMessage mailMessage = new MailMessage();
        //    mailMessage.From = new MailAddress(emailusername);

        //    UserRepository oUserRepository = new UserRepository();
        //    userModel user;
        //    if (type == "request")
        //    {
        //        //event create request, on request complete and on query raised
        //        //if (maildetails.eventid == 4 || maildetails.eventid == 12 || maildetails.eventid == 1)
        //        if (maildetails.eventid == 4 || maildetails.eventid == 12 || maildetails.eventid == 1 ||
        //            maildetails.eventid == 3 || maildetails.eventid == 2 || maildetails.eventid == 11 || maildetails.eventid == 9)
        //        {
        //            string requesttypeid = string.Empty; string creatormailid = string.Empty; int creatorid = 0;
        //            List<Dictionary<string, string>> reqDetails = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(fielddetails);

        //            foreach (Dictionary<string, string> lst in reqDetails)
        //            {
        //                foreach (KeyValuePair<string, string> item in lst)
        //                {
        //                    if (item.Key == "createdbyid")
        //                    {
        //                        creatorid = Convert.ToInt32(item.Value);
        //                    }

        //                }
        //            }
        //            userModel userdata = oUserRepository.FindByID(creatorid);
        //            mailMessage.CC.Add(userdata.emailid);


        //        }

        //    }


        //    //to groupdetails

        //    //MailGroupDetailRepository omailconfig = new MailGroupDetailRepository();
        //    //IEnumerable<mailgroupdetailModel> omailgroupModel;
        //    ////mail group array
        //    //var jsonObjMailGroup = JObject.Parse(maildetails.groupmapped);

        //    //JArray mailgroupids = (JArray)jsonObjMailGroup["mailgroups"];
        //    //if (mailgroupids.Count > 0)
        //    //{
        //    //    string groupemails = getGroupEmailidfromjson(mailgroupids);
        //    //    string tomailids = groupemails.Split('|')[0];
        //    //    string ccmailids = groupemails.Split('|')[1];

        //    //    if (groupemails != "")
        //    //    {
        //    //        if (!String.IsNullOrEmpty(tomailids))
        //    //            mailMessage.To.Add(tomailids);
        //    //        if (!String.IsNullOrEmpty(ccmailids))
        //    //            mailMessage.CC.Add(ccmailids);
        //    //    }
        //    //}
        //    string externaltomailids = "";
        //    if (maildetails.externalto != null)
        //    {
        //        if (JArray.Parse(maildetails.externalto).Count() > 0)
        //        {
        //            foreach (JToken mailids in JArray.Parse(maildetails.externalto))
        //            {
        //                if (mailids.ToString() != null && mailids.ToString() != "")
        //                {
        //                    {
        //                        if (externaltomailids == "")
        //                            externaltomailids = mailids.ToString();
        //                        else
        //                            externaltomailids = externaltomailids + "," + mailids.ToString();
        //                    }
        //                }
        //            }
        //        }
        //    }

        //    string externalccmailids = "";
        //    if (maildetails.externalcc != null && JArray.Parse(maildetails.externalcc).Count > 0)
        //    {
        //        foreach (JToken mailids in JArray.Parse(maildetails.externalcc))
        //        {
        //            if (mailids.ToString() != null && mailids.ToString() != "")
        //            {
        //                {
        //                    if (externalccmailids == "")
        //                        externalccmailids = mailids.ToString();
        //                    else
        //                        externalccmailids = externalccmailids + "," + mailids.ToString();
        //                }
        //            }
        //        }
        //    }
        //    //code to handle allocation external mailids


        //    // string allocationexternaltomailids = "";
        //    if (type.ToString().ToLower() == "formallocation")

        //    {
        //        if (fielddetails != null && fielddetails != "")
        //        {
        //            if (JArray.Parse(fielddetails).Count() > 0)
        //            {
        //                foreach (JToken mailids in JArray.Parse(fielddetails))
        //                {
        //                    if (mailids.ToString() != null && mailids.ToString() != "")
        //                    {
        //                        if (externaltomailids == "")
        //                            externaltomailids = mailids.ToString();
        //                        else
        //                            externaltomailids = externaltomailids + "," + mailids.ToString();
        //                        //mailMessage.To.Add(mailids.ToString());
        //                        //{
        //                        //if (allocationexternaltomailids == "")
        //                        //    allocationexternaltomailids = mailids.ToString();
        //                        //else
        //                        //    allocationexternaltomailids = allocationexternaltomailids + "," + mailids.ToString();
        //                        //}
        //                    }
        //                }
        //            }
        //        }
        //    }


        //    if (!String.IsNullOrEmpty(externaltomailids) && !String.IsNullOrWhiteSpace(externaltomailids))
        //        mailMessage.To.Add(externaltomailids);
        //    if (!String.IsNullOrEmpty(externalccmailids) && !String.IsNullOrWhiteSpace(externalccmailids))
        //        mailMessage.CC.Add(externalccmailids);



        //    //to mail id
        //    var jsonObjto = JObject.Parse(maildetails.mailto);
        //    JArray mailidto = (JArray)jsonObjto["mailto"];
        //    string toemailids = string.Empty;
        //    if (mailidto.Count > 0)
        //    {
        //        toemailids = getemailidfromjson(mailidto);
        //        if (toemailids != "")
        //            mailMessage.To.Add(toemailids);
        //    }
        //    //cc mail id
        //    var jsonObjcc = JObject.Parse(maildetails.mailcc);
        //    JArray mailidcc = (JArray)jsonObjcc["mailcc"];

        //    if (mailidcc.Count > 0)
        //    {
        //        string ccemailids = string.Empty;
        //        ccemailids = getemailidfromjson(mailidcc);
        //        if (ccemailids != "")
        //            mailMessage.CC.Add(ccemailids.ToString());
        //    }


        //    mailMessage.Body = sbody.ToString();
        //    mailMessage.IsBodyHtml = true;

        //    if (type.ToString().ToLower() == "ftp" || type.ToString().ToLower() == "laat")
        //    {
        //        mailMessage.Subject = maildetails.subject.Replace("$$currentdate", DateTime.Now.ToString("MM/dd/yyyy"));
        //    }
        //    else
        //    {
        //        mailMessage.Subject = maildetails.subject;
        //    }
        //    if (type.ToString().ToLower() == "form")
        //    {
        //        string res = subjectFieldsReplacement(maildetails, fielddetails, type);
        //        if (res != string.Empty)
        //            mailMessage.Subject = res;
        //    }
        //    if (type.ToString().ToLower() == "request")
        //    {
        //        string res = subjectFieldsReplacement(maildetails, fielddetails, type);
        //        if (res != string.Empty)
        //            mailMessage.Subject = res;
        //    }

        //    try
        //    {
        //        client.Send(mailMessage);
        //        s = "success";
        //    }

        //    catch (Exception e2)
        //    {
        //        s = e2.Message;
        //        if (s.ToLower().Contains(':'))
        //        {
        //            string[] tokens = s.Split(':');
        //            s = tokens[2].ToString();
        //        }
        //    }
        //    var userId = "0";

        //    if (type != "formallocation")
        //    {
        //        var claimsIdentity = WK_KLI_LAPS_Service.App_Data.AppContext.Current.User.Identity as ClaimsIdentity;
        //        userId = claimsIdentity.FindFirst(ClaimTypes.Name)?.Value;
        //    }
        //    var to = mailMessage.To;
        //    var cc = mailMessage.CC;
        //    string allmailids = string.Empty;
        //    for (int i = 0; i < to.Count; i++)
        //    {
        //        allmailids = allmailids + to[i].ToString() + ',';
        //        // allmailids =
        //    }
        //    for (int i = 0; i < cc.Count; i++)
        //    {
        //        allmailids = allmailids + cc[i].ToString();
        //        // allmailids =
        //    }
        //    sentemailhistoryModel osentemailhistory = new sentemailhistoryModel();
        //    osentemailhistory.emailid = allmailids;
        //    osentemailhistory.Msg = sbody.ToString();
        //    osentemailhistory.status = s.ToString();
        //    //osentemailhistory.eventdetails = maildetails.evenname;
        //    osentemailhistory.sentby = Convert.ToInt32(userId);
        //    int saveresult = emailhistorysave(osentemailhistory);

        //    return s;

        //}

        private StringBuilder getmailcontentformated(string mailcontent, string typedetails)
        {
            StringBuilder sbody = new StringBuilder();

            MatchCollection myMatchCollection = Regex.Matches(mailcontent, @"\$\w+(?:.(\w+))?");
            foreach (Match myMatch in myMatchCollection)
            {
                //Console.WriteLine(myMatch);
                var fieldname = Regex.Replace(myMatch.Value.ToString(), @"\$|\s+(?=\w+$)", "");
                JArray jsonArray = JArray.Parse(typedetails);
                JObject array = JObject.Parse(jsonArray[0].ToString());

                foreach (KeyValuePair<String, JToken> app in array)
                {

                    var appName = app.Key;
                    if (fieldname.ToLower() == appName.ToLower())
                    {
                        var appValue = (String)app.Value;
                        if ((appValue != string.Empty) && (appValue != null) && (appValue != null))
                        {
                            //if (appName.Contains("size"))
                            //{
                            //    appValue = FileSizeFormatter.FormatSize(Convert.ToInt32(appValue));
                            //}

                            var regex = new Regex(Regex.Escape("$" + myMatch.Value.ToString()));
                            mailcontent = regex.Replace(mailcontent, appValue, 1);

                        }
                        else
                        {
                            var regex = new Regex(Regex.Escape("$" + myMatch.Value.ToString()));
                            mailcontent = regex.Replace(mailcontent, "-", 1);
                            // mailcontent = mailcontent.Replace("$" + myMatch.Value.ToString(), "");
                        }

                    }
                }
                if (myMatch.Value.ToString().Contains(fieldname.ToLower()) && myMatch.Value.ToString() != "$documentlink" && myMatch.Value.ToString() != "$downloadlink")
                {
                    mailcontent = mailcontent.Replace("$" + myMatch.Value.ToString(), "");
                }

            }
            sbody.Append(mailcontent);
            return sbody;


        }

        public DataTable JsonStringToDataTable(string jsonString)
        {
            DataTable dt = new DataTable();
            string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
            List<string> ColumnsName = new List<string>();
            foreach (string jSA in jsonStringArray)
            {
                string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
                foreach (string ColumnsNameData in jsonStringData)
                {
                    try
                    {
                        int idx = ColumnsNameData.IndexOf(":");
                        string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
                        if (!ColumnsName.Contains(ColumnsNameString))
                        {
                            ColumnsName.Add(ColumnsNameString);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message.ToString());
                        throw new Exception(string.Format("Error Parsing Column Name : {0}", ColumnsNameData));
                    }
                }
                break;
            }
            foreach (string AddColumnName in ColumnsName)
            {
                dt.Columns.Add(AddColumnName);
            }
            foreach (string jSA in jsonStringArray)
            {
                string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
                DataRow nr = dt.NewRow();
                foreach (string rowData in RowData)
                {
                    try
                    {
                        int idx = rowData.IndexOf(":");
                        string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
                        string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
                        nr[RowColumns] = RowDataString;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message.ToString());
                        continue;
                    }
                }
                dt.Rows.Add(nr);
            }
            return dt;
        }

        public int emailhistorysave(sentemailhistoryModel data)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                int result = 0;
                string input = JsonConvert.SerializeObject(data);
                const string query = @"public.spmailsenthistory";
                var param = new DynamicParameters();
                param.Add("inputjsonstr", dbType: DbType.String, value: input, direction: ParameterDirection.Input);
                param.Add("mode_p", dbType: DbType.String, value: "insert", direction: ParameterDirection.Input);
                result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();
                return result;
            }
        }

        public int emailhistorystatusupdate(sentemailhistoryModel data)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                int result = 0;
                string input = JsonConvert.SerializeObject(data);
                const string query = @"public.spmailsenthistory";
                var param = new DynamicParameters();
                param.Add("inputjsonstr", dbType: DbType.String, value: input, direction: ParameterDirection.Input);
                param.Add("mode_p", dbType: DbType.String, value: "update", direction: ParameterDirection.Input);
                result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();
                return result;
            }
        }

        public string getemailidfromjson(JArray mailidjson)
        {
            string emailids = "";
            UserRepository oUserRepository = new UserRepository();
            userModel user;

            foreach (JToken maildetails in mailidjson)
            {
                if (maildetails["userid"] != null && (string)maildetails["userid"] != "")
                {
                    user = new userModel();
                    user = (userModel)oUserRepository.FindByID((int)maildetails["userid"]);
                    if (user.emailid != "" && user.emailid != null)
                    {
                        if (emailids == "")
                            emailids = user.emailid;
                        else
                            emailids = emailids + "," + user.emailid;
                    }
                }
            }
            return emailids;
        }

        public void ErrorLog(Exception ex)
        {
            try
            {
                //string filePath = @"C:\Error.txt";
                //string a = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
                //DriveInfo cDrive = new DriveInfo(System.Environment.CurrentDirectory);
                //string b = cDrive.RootDirectory.ToString();
                //string c = AppDomain.CurrentDomain.BaseDirectory;
                string d = System.IO.Directory.GetCurrentDirectory();
                //  File.WriteAllText(d, sb.ToString());
                using (StreamWriter writer = new StreamWriter(d + "\\error.log.txt", true))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("------------------------Error Log start----------------------------");
                    sb.AppendLine("Date:-" + DateTime.Now.ToString());
                    sb.AppendLine("Application Name :" + ex.Source);
                    sb.AppendLine("Error Message :" + ex.Message);
                    sb.AppendLine("Method Name :" + ex.StackTrace);
                    sb.AppendLine("------------------------Error Log End----------------------------");
                    writer.WriteLine(sb.ToString());
                    writer.Close();
                    // tw.WriteLine("The next line!");
                };
            }
            catch (Exception)
            {

            }
            //System.IO.File.WriteAllText(d+"\\error.log.txt", sb.ToString());
        }
        public void WriteLog(string logtxt, string method)
        {
            try
            {

                string d = System.IO.Directory.GetCurrentDirectory();
                using (StreamWriter writer = new StreamWriter(d + "\\log.log.txt", true))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("------------------------ Log start----------------------------");
                    sb.AppendLine("Date:-" + DateTime.Now.ToString());
                    sb.AppendLine("Method Name :" + method);
                    sb.AppendLine("Log Message :" + logtxt);

                    sb.AppendLine("------------------------ Log End----------------------------");
                    writer.WriteLine(sb.ToString());
                    writer.Close();
                    // tw.WriteLine("The next line!");
                };
            }
            catch (Exception)
            {

            }
            //System.IO.File.WriteAllText(d+"\\error.log.txt", sb.ToString());
        }
        public string removeUnwantedFieldName(string mailContent)
        {
            string returnvalue = string.Empty;
            MatchCollection myMatchCollection = Regex.Matches(mailContent, @"\$\$[^ ]+(?= |$)");
            if (myMatchCollection.Count != 0)
            {
                foreach (Match myMatch in myMatchCollection)
                {
                    mailContent = mailContent.Replace(myMatch.Value.ToString(), " ");
                    returnvalue = mailContent;
                }
            }
            else
                returnvalue = mailContent;
            return returnvalue;
        }

        public static string CombinedStringBuilder(List<int> list)
        {
            try
            {
                StringBuilder combindedString = new StringBuilder();
                foreach (var item in list)
                {
                    var strappend = item;
                    combindedString.Append(strappend).Append(",");
                }
                if (!string.IsNullOrEmpty(combindedString.ToString()))
                {
                    combindedString.Length = combindedString.Length - 1;
                }
                return combindedString.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public string GetServerDateRep(string mode)
        {
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    dbConnection.Open();
                    var param = new DynamicParameters();
                    const string query = @"public.spselectserverdatetime";
                    param.Add("mode_p", dbType: DbType.String, value: mode.ToLower(), direction: ParameterDirection.Input);
                    return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                ErrorLog(ex);
                return ex.Message;
            }
        }

        public void useractivityAdd(useractivitylogModel userlog)
        {

            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                var claimsIdentity = WK_KLI_LAPS_Service.App_Data.AppContext.Current.User.Identity as ClaimsIdentity;
                var userId = claimsIdentity.FindFirst(ClaimTypes.Name)?.Value;
                //var accessToken = LotusNotesService.App_Data.AppContext.Current.Request.Headers["Authorization"];

                userlog.userid = Convert.ToInt32(userId);
                userlog.ipaddress = WK_KLI_LAPS_Service.App_Data.AppContext.Current.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress?.ToString();
                string output = JsonConvert.SerializeObject(userlog);
                DynamicParameters param = new DynamicParameters();
                param.Add("inputjsonstr", output);
                param.Add("mode_p", "insert");
                dbConnection.Open();
                dbConnection.Execute("spuseractivitylog", param, commandType: CommandType.StoredProcedure);
            }

        }

        public string subjectFieldsReplacement(mailconfigModel maildetails, string fielddetails, string type)
        {
            string result = "";
            MatchCollection myMatchCollection = Regex.Matches(maildetails.subject, @"\$\$[^ ]+(?= |$)");
            JArray jsonArray = JArray.Parse(fielddetails);
            JObject fieldData = JObject.Parse(jsonArray[0].ToString());
            if (myMatchCollection.Count != 0)
            {
                result = maildetails.subject;
                foreach (Match myMatch in myMatchCollection)
                {
                    var splitDollar = myMatch.ToString().Split("$$");
                    string replaceData = string.Empty;
                    if (splitDollar.Count() != 0)
                    {
                        JProperty prop = fieldData.Properties().FirstOrDefault(p => p.Name.ToLower().Contains(splitDollar[1].ToString().ToLower()));
                        replaceData = prop != null ? prop.Value.ToString() : "";
                        result = result.Replace(myMatch.ToString(), replaceData);
                    }
                }
            }
            return result;
        }

        public StringBuilder formatMailContent(string mailcontent, object details)
        {
            StringBuilder sbody = new StringBuilder();
            MatchCollection myMatchCollection = Regex.Matches(mailcontent, @"\$\w+(?:.(\w+))?");

            foreach (Match myMatch in myMatchCollection)
            {
                var fieldname = Regex.Replace(myMatch.Value.ToString(), @"\$|\s+(?=\w+$)", "");
                Type myType = details.GetType();
                IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
                foreach (PropertyInfo prop in props)
                {
                    if (prop.Name.ToLower() == fieldname.ToString().ToLower())
                    {
                        var propValue = (String)prop.GetValue(details, null);
                        if ((propValue != null) && (propValue.ToString() != string.Empty))
                        {
                            var regex = new Regex(Regex.Escape("$" + myMatch.Value.ToString()));
                            mailcontent = regex.Replace(mailcontent, propValue.ToString(), 1);
                        }
                        else
                        {
                            var regex = new Regex(Regex.Escape("$" + myMatch.Value.ToString()));
                            mailcontent = regex.Replace(mailcontent, "-", 1);
                        }
                    }
                }
                if (myMatch.Value.ToString().Contains(fieldname.ToLower()))
                {
                    mailcontent = mailcontent.Replace("$" + myMatch.Value.ToString(), "");
                }

            }
            sbody.Append(mailcontent);
            return sbody;


        }

        //get the list of available action list
        public IEnumerable<object> getRoleMappedMenu(int userid)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.sprolemappedmenu";
                param.Add("userid_p", dbType: DbType.Int32, value: userid, direction: ParameterDirection.Input);
                param.Add("parent_p", dbType: DbType.Int32, value: 0, direction: ParameterDirection.Input);
                return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        //Common function to Execute Stored procedure to select records
        public object ExecuteSP_ReturnList(string spname, string inputjsonstring, string mode)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                param.Add("inputjsonstr", inputjsonstring);
                param.Add("mode_p", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
            }
        }
        //ccwms
        public object CCExecuteSP_ReturnList(string spname, Int64 userid, Int64 projecdefid)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                //param.Add("inputjsonstr", inputjsonstring);
                param.Add("p_userid", dbType: DbType.Int32, value: userid, direction: ParameterDirection.Input);
                param.Add("p_projectdefid", dbType: DbType.Int32, value: projecdefid, direction: ParameterDirection.Input);
                return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
            }
        }
        public object CCExecuteSP_ReturnList1(string spname, lotmasterModel olotmasterr)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                param.Add("p_jobid", dbType: DbType.Int64, value: olotmasterr.jobid, direction: ParameterDirection.Input);
                param.Add("p_projectcode", dbType: DbType.String, value: olotmasterr.projectid, direction: ParameterDirection.Input);
                param.Add("p_joburl", dbType: DbType.String, value: olotmasterr.url, direction: ParameterDirection.Input);
                param.Add("p_bitnumber", dbType: DbType.String, value: olotmasterr.biddate, direction: ParameterDirection.Input);
                param.Add("p_userid", dbType: DbType.Int64, value: olotmasterr.createdby, direction: ParameterDirection.Input);
                return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        //Common function to Execute Stored procedure for insert update and delete 
        public int ExecuteSP_ReturnInt(string spname, object data, string mode, string loglabel)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                string input = JsonConvert.SerializeObject(data);
                int result = 0;

                string query = spname;
                var param = new DynamicParameters();
                param.Add("inputjsonstr", dbType: DbType.String, value: input, direction: ParameterDirection.Input);
                param.Add("mode_p", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();

                //code to add user activity log
                if (result != 0)
                {
                    userlogmodel = new useractivitylogModel();
                    userlogmodel.useraction = loglabel + result;
                    userlogmodel.description = loglabel + result;
                    useractivityAdd(userlogmodel);
                }
                return result;
            }
        }


        //Check the given name is exists or not
        public bool CheckExists(string spname, string mode, object inputjsonval)
        {
            bool result = false;
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                string input = JsonConvert.SerializeObject(inputjsonval);
                var param = new DynamicParameters();
                string query = spname;
                param.Add("inputjsonstr", input);
                param.Add("mode_p", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                var _list = dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).ToList();

                if (_list.Count() > 0 && _list.ToList()[0] != null)
                    result = true;
                return result;
            }
        }

        public bool CheckExistsWithMessage(string spname, string mode, object inputjsonval, ref string message)
        {
            bool result = false;
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {

                dbConnection.Open();
                string input = JsonConvert.SerializeObject(inputjsonval);
                var param = new DynamicParameters();
                string query = spname;
                param.Add("inputjsonstr", input);
                param.Add("mode_p", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                var _list = dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).ToList();

                if (_list.Count() > 0 && _list.ToList()[0] != null)
                {
                    message = _list[0];

                    JObject obj = JObject.Parse(_list[0]);
                    string msg = (string)obj["message"];
                    if (msg.ToString().Trim().Length > 0)
                        result = true;
                }
                return result;
            }
        }
        //Common function to Execute Stored procedure to select records
        public lotmasterModel ExecuteSP_ReturnListForLot(string spname, string inputjsonstring, string mode)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {

                bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                WriteLog(isWindows.ToString(), "ExecuteSP_ReturnListForLot:isWindows");
                if (isWindows)
                {

                    dbConnection.Open();
                    var param = new DynamicParameters();
                    string query = spname;
                    var ds = JsonConvert.DeserializeObject<lotmasterModel>(inputjsonstring);
                    param.Add("p_tranid", dbType: DbType.Int32, value: ds.transactionid, direction: ParameterDirection.Input);
                    param.Add("p_lotid", dbType: DbType.Int32, value: ds.lotid, direction: ParameterDirection.Input);
                    param.Add("p_option", dbType: DbType.String, value: ds.option, direction: ParameterDirection.Input);
                    param.Add("p_ostype", dbType: DbType.String, value: "Windows", direction: ParameterDirection.Input);
                    return dbConnection.Query<lotmasterModel>(query, param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                }
                else
                {
                    dbConnection.Open();
                    var param = new DynamicParameters();
                    string query = spname;
                    var ds = JsonConvert.DeserializeObject<lotmasterModel>(inputjsonstring);
                    param.Add("p_tranid", dbType: DbType.Int32, value: ds.transactionid, direction: ParameterDirection.Input);
                    param.Add("p_lotid", dbType: DbType.Int32, value: ds.lotid, direction: ParameterDirection.Input);
                    param.Add("p_option", dbType: DbType.String, value: ds.option, direction: ParameterDirection.Input);
                    param.Add("p_ostype", dbType: DbType.String, value: "Linux", direction: ParameterDirection.Input);
                    return dbConnection.Query<lotmasterModel>(query, param, commandType: CommandType.StoredProcedure).FirstOrDefault();
                }
            }
        }

        //Common function to Execute Stored procedure to select records with out mode
        public object ExecuteSP_ReturnListwithoutmode(string spname, string inputjsonstring)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                param.Add("inputjsonstr", inputjsonstring);
                return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        public object ExecuteSP_ReturnList1(string spname, string inputjsonstring)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                param.Add("inputjsonstr", inputjsonstring);

                var list = dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).ToList();
                return list[0];
            }
        }
        public object Vendor_ExecuteSP_ReturnList1(string spname, string inputjsonstring, string mode)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                param.Add("inputjsonstr", inputjsonstring);
                param.Add("mode_p", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                var list = dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).ToList();
                return list[0];
            }
        }
        public string GetServerPath(string transactionid, string mode, bool createdir = false)
        {
            string serverpath = string.Empty;
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                    if (isWindows)
                    {
                        dbConnection.Open();
                        var param = new DynamicParameters();
                        const string query = @"public.spusrserverpathinfo";
                        param.Add("p_tranid", dbType: DbType.Int32, value: Convert.ToInt32(transactionid), direction: ParameterDirection.Input);
                        param.Add("p_lotid", dbType: DbType.Int32, value: null, direction: ParameterDirection.Input);
                        param.Add("p_option", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                        param.Add("p_ostype", dbType: DbType.String, value: "Windows", direction: ParameterDirection.Input);
                        IEnumerable<servermasterModel> sm = dbConnection.Query<servermasterModel>(query, param, commandType: CommandType.StoredProcedure);
                        if (createdir)
                        {
                            serverpath = FormatPath(sm.First().serverpath.ToString());
                            Directory.CreateDirectory(Path.Combine(serverpath, "IN"));
                            Directory.CreateDirectory(Path.Combine(serverpath, "OUT"));
                        }
                        else
                        {
                            serverpath = FormatPath(sm.First().serverpath.ToString());
                        }
                    }
                    else
                    {
                        dbConnection.Open();
                        var param = new DynamicParameters();
                        const string query = @"public.spusrserverpathinfo";
                        param.Add("p_tranid", dbType: DbType.Int32, value: Convert.ToInt32(transactionid), direction: ParameterDirection.Input);
                        param.Add("p_lotid", dbType: DbType.Int32, value: null, direction: ParameterDirection.Input);
                        param.Add("p_option", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                        param.Add("p_ostype", dbType: DbType.String, value: "Linux", direction: ParameterDirection.Input);
                        IEnumerable<servermasterModel> sm = dbConnection.Query<servermasterModel>(query, param, commandType: CommandType.StoredProcedure);
                        if (createdir)
                        {
                            serverpath = sm.First().serverpath.ToString();
                            Directory.CreateDirectory(Path.Combine(serverpath, "IN"));
                            Directory.CreateDirectory(Path.Combine(serverpath, "OUT"));
                        }
                        else
                        {
                            serverpath = sm.First().serverpath.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return serverpath;
            }
            return serverpath;
        }


        public string FormatPath(string inputpath)
        {
            try
            {
                inputpath = inputpath.Replace("/", "\\");
                inputpath = inputpath.Replace("\\\\", "");
                inputpath = System.Text.RegularExpressions.Regex.Replace(inputpath, @"\\\\", "", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            return string.Concat("\\\\", inputpath);
        }
        //get the list of available action list
        public IEnumerable<object> getRoleMappedMenuDashboard(int userid)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.sprolemappedmenudashboard";
                param.Add("userid_p", dbType: DbType.Int32, value: userid, direction: ParameterDirection.Input);
                param.Add("parent_p", dbType: DbType.Int32, value: 0, direction: ParameterDirection.Input);
                return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
            }
        }
        //To activate or deactivate the selected record
        public int UpdateMailbox(object data, string mastername)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                int result = 0;
                string input = JsonConvert.SerializeObject(data);
                string query = @"public.sp" + mastername + "master";
                var param = new DynamicParameters();
                param.Add("inputjsonstr", dbType: DbType.String, value: input, direction: ParameterDirection.Input);
                param.Add("mode_p", dbType: DbType.String, value: "update", direction: ParameterDirection.Input);
                result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();

                if (result != 0)
                {
                    userlogmodel = new useractivitylogModel();
                    userlogmodel.useraction = "Update " + mastername;
                    userlogmodel.description = "Update " + mastername + ".Update Id is " + result.ToString();
                    useractivityAdd(userlogmodel);
                }
                return result;
            }
        }

        public static object ExecuteSP_ReturnList2(string spname, string inputjsonstring, string mode)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                string query = spname;
                param.Add("inputjsonstr", inputjsonstring);
                param.Add("mode_p", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                var list = dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure).ToList();
                return list[0];
            }
        }
        //get the list of available action list
        public IEnumerable<object> getOutlineByoutlineconfigId(int outlineconfigId)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spoutlineconfigdetailselect";
                param.Add("outlineconfigid_p", dbType: DbType.Int32, value: outlineconfigId, direction: ParameterDirection.Input);
                param.Add("parent_p", dbType: DbType.Int32, value: 0, direction: ParameterDirection.Input);
                param.Add("mode_p", dbType: DbType.String, value: "GetOutlineCIDdata", direction: ParameterDirection.Input);
                return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
            }
        }
        public object UpdateOutlineStageMapping(string inputstr, string mode)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                string query = @"public.spoutlineconfigstagemapping";
                var param = new DynamicParameters();
                param.Add("inputjsonstr", dbType: DbType.String, value: inputstr, direction: ParameterDirection.Input);
                param.Add("mode_p", dbType: DbType.String, value: mode, direction: ParameterDirection.Input);
                return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        public IEnumerable<object> FindActiveMasterTables()
        {
            using (System.Data.IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spmastertableselect";
                return dbConnection.Query<object>(query, null, commandType: CommandType.StoredProcedure);
            }
        }

        //code to get field alias name
        public IEnumerable<object> FindActiveFieldAlias()
        {
            using (System.Data.IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spfieldaliasselect";
                return dbConnection.Query<object>(query, null, commandType: CommandType.StoredProcedure);
            }
        }

        public IEnumerable<object> GetFormConfigDashboardField(int formconfigid)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spformconfigdashboardfieldselect";
                param.Add("smartchartconfigid_p", formconfigid);
                return dbConnection.Query<object>(query, param, commandType: CommandType.StoredProcedure);
            }
        }
        public string GetBackupfolder(string pathfold)
        {
            try
            {
                int i = 1;
            rechck:;
                if (Directory.Exists(string.Join("", pathfold, "\\V", i.ToString("000"))))
                {
                    i++;
                    goto rechck;
                }
                else
                {
                    Directory.CreateDirectory(string.Join("", pathfold, "\\V", i.ToString("000")));
                    //Directory.CreateDirectory(string.Join("", pathfold, "\\V", i.ToString("000")) + "\\OUT");
                    return pathfold + "\\V" + i.ToString("000");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                //ErrorLogger.environment = enviroment; ErrorLogger.errorLog.WriteErrorLog(new ErrorTranslate { TranID = Convert.ToInt64(tranid), ErrorMessage = ex.Message.ToString() });
                return pathfold;
            }
        }
        public string CopyDirectory(string sourceDir, string destinationDirc)
        {
            string Name = "";
            DirectoryInfo source = new DirectoryInfo(sourceDir);
            DirectoryInfo destination = new DirectoryInfo(destinationDirc);
            if (!destination.Exists)
            {
                destination.Create();
            }
            if (!source.Exists)
            {
                return "erorr";
            }
            FileInfo[] files = source.GetFiles();
            foreach (FileInfo file in files)
            {
                if (file.Name.ToLower().Trim() != "thumbs.db")
                {
                    Name = file.Name;
                    string Dest = System.IO.Path.Combine(destination.FullName, file.Name);
                    if (System.IO.File.Exists(Dest))
                    {
                        System.IO.File.Delete(Dest);
                    }
                    if (!System.IO.File.Exists(Dest))
                    {
                        file.CopyTo(Dest, true);
                    }
                }
            }
            DirectoryInfo[] dirs = source.GetDirectories().Where(x => x.ToString() != "V001").ToArray<DirectoryInfo>();
            foreach (DirectoryInfo dir in dirs)
            {
                if (dir.Name != "V001")
                {
                    string destinationDir = System.IO.Path.Combine(destination.FullName, dir.Name);
                    string destinationDir1 = dir.FullName;
                    CopyDirectory(destinationDir1, destinationDir);
                }
            }
            return Name;
        }
        public IEnumerable<object> GetActiveVersions()
        {
            using (System.Data.IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spreleasenotesselect";
                return dbConnection.Query<object>(query, param, commandType: CommandType.StoredProcedure);
            }
        }
        //get the list of available action list
        public IEnumerable<object> getOutlineDetailByoutlineconfigId(int outlineconfigId)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                var param = new DynamicParameters();
                const string query = @"public.spoutlineconfigdetailselect";
                param.Add("outlineconfigid_p", dbType: DbType.Int32, value: outlineconfigId, direction: ParameterDirection.Input);
                param.Add("mode_p", dbType: DbType.String, value: "getallbyoutlineconfigid", direction: ParameterDirection.Input);
                return dbConnection.Query<string>(query, param, commandType: CommandType.StoredProcedure);
            }
        }

        public string GetServerPathbatch(string transactionid, Int32 id, bool createdir = false, string serverinfo = "")
        {
            string serverpath = string.Empty;
            try
            {
                using (IDbConnection dbConnection = ConnectionBase.Connection)
                {
                    bool isWindows = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                    if (isWindows)
                    {
                        dbConnection.Open();
                        var param = new DynamicParameters();
                        const string query = @"public.spusrserverpathinfobatch";
                        param.Add("p_lotid", dbType: DbType.Int32, value: Convert.ToInt32(transactionid), direction: ParameterDirection.Input);
                        param.Add("p_batchid", dbType: DbType.Int32, value: Convert.ToInt32(id), direction: ParameterDirection.Input);
                        param.Add("p_option", dbType: DbType.String, value: serverinfo, direction: ParameterDirection.Input);
                        param.Add("p_ostype", dbType: DbType.String, value: "Windows", direction: ParameterDirection.Input);
                        IEnumerable<servermasterModel> sm = dbConnection.Query<servermasterModel>(query, param, commandType: CommandType.StoredProcedure);
                        if (createdir)
                        {
                            serverpath = FormatPath(sm.First().serverpath.ToString());
                            Directory.CreateDirectory(Path.Combine(serverpath, "IN"));
                            Directory.CreateDirectory(Path.Combine(serverpath, "OUT"));
                        }
                        else
                        {
                            serverpath = FormatPath(sm.First().serverpath.ToString());
                        }
                    }
                    else
                    {
                        dbConnection.Open();
                        var param = new DynamicParameters();
                        const string query = @"public.spusrserverpathinfobatch";
                        param.Add("p_lotid", dbType: DbType.Int32, value: Convert.ToInt32(transactionid), direction: ParameterDirection.Input);
                        param.Add("p_batchid", dbType: DbType.Int32, value: Convert.ToInt32(id), direction: ParameterDirection.Input);
                        param.Add("p_option", dbType: DbType.String, value: serverinfo, direction: ParameterDirection.Input);
                        param.Add("p_ostype", dbType: DbType.String, value: "Linux", direction: ParameterDirection.Input);
                        IEnumerable<servermasterModel> sm = dbConnection.Query<servermasterModel>(query, param, commandType: CommandType.StoredProcedure);
                        if (createdir)
                        {
                            serverpath = sm.First().serverpath.ToString();
                            Directory.CreateDirectory(Path.Combine(serverpath, "IN"));
                            Directory.CreateDirectory(Path.Combine(serverpath, "OUT"));
                        }
                        else
                        {
                            serverpath = sm.First().serverpath.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return serverpath;
            }
            return serverpath;
        }
        public int addlog(object data, string mastername)
        {
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                string input = JsonConvert.SerializeObject(data);
                int result = 0;
                string query = @"public.sp" + mastername;
                var param = new DynamicParameters();
                param.Add("inputjsonstr", dbType: DbType.String, value: input, direction: ParameterDirection.Input);
                param.Add("mode_p", dbType: DbType.String, value: "insert", direction: ParameterDirection.Input);
                result = dbConnection.Query<int>(query, param, commandType: CommandType.StoredProcedure).First();
                return result;
            }
        }
        public class GrantFolderPermission : IDisposable
        {
            //  ServerInfo info = new ServerInfo();
            private bool id;
            Impartunate impartunate = null;
            CommonRepository oCommonRepository = new CommonRepository();
            public GrantFolderPermission(string pdefid, string transactionid = "", string lotid = "", string jobid = "")
            {
                var ds = new lotmasterModel();

                //var data = new
                //{
                //    transactionid = transactionid,
                //    lotid = 0,
                //    option = "logininfo"
                //};

                if (transactionid != "")
                {
                    var data = new
                    {
                        transactionid = transactionid,
                        lotid = 0,
                        option = "logininfo"
                    };
                    string inputstr = JsonConvert.SerializeObject(data);
                    ds = oCommonRepository.ExecuteSP_ReturnListForLot("spusrserverpathinfo", inputstr, "logininfo");
                }
                else if (pdefid != "")
                {
                    var data = new
                    {
                        transactionid = pdefid,
                        lotid = 0,
                        option = "serverinfo_projid"
                    };
                    string inputstr = JsonConvert.SerializeObject(data);
                    ds = oCommonRepository.ExecuteSP_ReturnListForLot("spusrserverpathinfo", inputstr, "serverinfo_projid");
                }

                // ds = info.GetDataTable("usr_server_path_info", info.GetNpgsqlParameter(transactionid, 0, "logininfo"));
                else if (lotid != "")
                {
                    var data = new
                    {
                        transactionid = 0,
                        lotid = lotid,
                        option = "loginlotinfo"
                    };
                    string inputstr = JsonConvert.SerializeObject(data);
                    ds = oCommonRepository.ExecuteSP_ReturnListForLot("spusrserverpathinfo", inputstr, "loginlotinfo");
                }

                // ds = info.GetDataTable("usr_server_path_info", info.GetNpgsqlParameter("0", Convert.ToInt32(lotid), "loginlotinfo"));
                // else if (jobid != "")
                // ds = info.GetDataTable("usr_server_path_info", info.GetNpgsqlParameterjob("0", "0", Convert.ToInt32(jobid), "loginjobinfo"));

                /*string query = @"select  lt.transactionid, sm.ipaddress, sm.username, sm.password, sm.domain  from lot_transaction as lt 
                                Left join lot_master lm on lt.lotid=lm.lotid 
                                left join job_master jm on lm.jobid = jm.jobid
                                left join project_definition pd on jm.projectdefinitionid = pd.projectdefinitionid
                                left join server_master sm on pd.fileserver = sm.serverid where lt.transactionid = '" + transid + "'";*/

                //using (DataSet ds = info.GetDataSet(query))
                //{
                if (ds != null)
                {

                    string username = ds.username;
                    string password = ds.password;
                    string domain = ds.domain;
                    impartunate = new Impartunate(username, password, domain);
                    impartunate.AllowAccesstoServer();
                }
                //}
            }

            public Impartunate GetImpartunate()
            {
                return impartunate;
            }

            public void Dispose()
            {
                if (id == true)
                    return;
                impartunate.RemoveServerAccess();
                impartunate = null;
                id = true;
                GC.SuppressFinalize(this);
            }

        }


        public class Impartunate
        {
            #region Impersonating User

            #region Impersonation
            static IntPtr tokenHandle;
            // static WindowsImpersonationContext impersonatedUser;
            private string impersUsername { get; set; }
            private string impersPwd { get; set; }
            private string impersDomain { get; set; }
            static WindowsIdentity newId;
            #endregion

            public Impartunate(string username, string password, string domain)
            {
                impersUsername = username;
                impersPwd = password;
                impersDomain = domain;
            }


            // public static WindowsImpersonationContext oImpersonatedUser;
            [DllImport("advapi32.dll", SetLastError = true)]
            private static extern bool LogonUser(string sUsername, string sDomain, string sPassword, int iLogonType, int iLogonProvider, ref IntPtr oToken);

            [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
            private static extern bool CloseHandle(IntPtr oHandle);

            //public bool AllowAccesstoServer()
            public WindowsIdentity AllowAccesstoServer()
            {
                try
                {
                    tokenHandle = IntPtr.Zero;
                    bool Result = LogonUser(impersUsername, impersDomain, impersPwd, 2, 0, ref tokenHandle);
                    if (Result)
                    {
                        newId = new WindowsIdentity(tokenHandle);
                        //impersonatedUser = newId.Impersonate();
                        //return true;
                        return newId;
                    }
                    else
                    {
                        //return false;
                        return null;
                    }
                }
                catch (Exception ex)
                {
                    //return false;
                    return null;
                }
            }

            public void RemoveServerAccess()
            {
                try
                {
                    //if (impersonatedUser != null)
                    //{
                    //    impersonatedUser.Undo();
                    //}
                    if (tokenHandle != IntPtr.Zero)
                    {
                        CloseHandle(tokenHandle);
                    }
                }
                catch (Exception ex) { }
            }

            private void ImpersonateUser()
            {
                System.IO.FileInfo localFileLastModified;
                System.IO.FileInfo serverFileLastModified;
                if (AllowAccesstoServer() == null)
                {
                    RemoveServerAccess();
                }
            }

            #endregion
        }

    }

}




