#region Using Namespace
using System;
using System.Collections.Generic;
using System.Web;
using System.Configuration;
using System.Web.Security;
using System.Web.UI;
using Sapphire.Ohu.BusinessEntity.Framework.BaseFrameworkBE;
using Sapphire.Ohu.BusinessLogic.Framework.BaseFrameworkBL.Security;
using Sapphire.Ohu.BaseFramework.Security;
using Sapphire.Ohu.Web.SessionHelper;
using Sapphire.Ohu.BaseFramework.Utilities;
using Sapphire.Ohu.Web.Helper;
using System.Web.UI.WebControls;
using System.Threading;
using System.Data;
using System.IO;
using System.Xml.Linq;
using System.Linq;
using System.Net;
using Sapphire.Ohu.BusinessEntity.Framework.UtilityBE;
using Sapphire.Ohu.BusinessLogic.Framework.UtilityBL;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using Sapphire.Ohu.BusinessEntity.Component.AlertBE;
using Sapphire.Ohu.BusinessLogic.Component.AlertBL;
using System.Xml;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
//using Sapphire.Ohu.License.LicenseManager;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Web.Services;

using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using Sapphire.Vidyalaya.BusinessLogic.Business.Common.CommonBL;
using Sapphire.Vidyalaya.BusinessEntity.Business.ZCRMBE;
using Sapphire.Vidyalaya.Components.Alert.AlertNotification;
#endregion

public partial class Login : Page
{

    #region Constant

    public readonly bool AllowMoreSessions = Convert.ToBoolean(ConfigurationManager.AppSettings["AllowMoreSessions"].ToString().ToLower() ?? "false");
    internal String hashedPassword = string.Empty;
    string VersionNumber = string.Empty;
    bool IsNewVersion = false;
    private Int32 OrgGroupId = 0;
    private string LoginAuthorizationUser = string.Empty;
    private Int32 ErpOrgId = 0;
    public string ErpUsername = string.Empty;
    public string ErpPassword = string.Empty;
    public int PaymentResponse = 0;
    public string ErpAPIUrl = string.Empty;
    #endregion

    #region Service Client

    /// <summary>
    /// Gets the security service client.
    /// </summary>
    /// <returns></returns>
    private SecurityService GetSecurityServiceClient()
    {
        return new SecurityService();
    }

    private CommonFunctions CommonFunctionsServiceClient()
    {
        return new CommonFunctions();
    }

    private ERPCommonFunction ErpCommonFunctionService
    {
        get
        {
            return new ERPCommonFunction();
        }
    }
    #endregion

    #region Events
    bool ReturnValue()
    {
        return false;
    }
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    /// 
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            bool success = Int32.TryParse(Request.QueryString["OrgGroupId"], out OrgGroupId);
            if (Request.QueryString["PaymentResponse"] != null)
                PaymentResponse = int.Parse(Request.QueryString["PaymentResponse"]);
            if (!success)
            {
                string messageValue1 = Request.QueryString["NOL"] ?? "0";
                if (messageValue1.Equals("-1"))
                {
                    bool success1 = Int32.TryParse(ConfigurationManager.AppSettings["DefaultOrgGroupId"], out OrgGroupId);
                    if (!success1)
                    {
                        ErrorLabel.Text = "Invalid OrgGroupId";
                        ErrorLabel.Visible = true;
                        return;
                    }
                    else
                    {
                        string url = HttpContext.Current.Request.Url.AbsoluteUri;
                        string[] separateURL = url.Split('?');

                        Response.Redirect(separateURL[0] + "?OrgGroupId=" + ConfigurationManager.AppSettings["DefaultOrgGroupId"]);
                    }
                }
                else
                {
                    ErrorLabel.Text = "Invalid OrgGroupId";
                    ErrorLabel.Visible = true;
                    return;
                }
            }

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ErpAPIUrl"]))
                ErpAPIUrl = ConfigurationManager.AppSettings["ErpAPIUrl"];
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["DefaultErpOrgId"]))
                ErpOrgId = Convert.ToInt32(ConfigurationManager.AppSettings["DefaultErpOrgId"]);
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ErpUsername"]))
                ErpUsername = ConfigurationManager.AppSettings["ErpUsername"];
            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["ErpPassword"]))
                ErpPassword = ConfigurationManager.AppSettings["ErpPassword"];

            //Change for url session time out not working mantis id :0027381
            OrgGroupIdHiddenField.Value = Request.QueryString["OrgGroupId"];
            LoginAuthorizationUser = ConfigurationHelper.GetUserConfigurationValueDirect(int.Parse(OrgGroupIdHiddenField.Value.ToString()), 0, 0, "Security.LoginAuthorizationUser");

            var xdoc = XDocument.Load(Server.MapPath("~/ContentTemplates/Brand/BrandConfiguration.xml"));
            var parameters = xdoc.Descendants("item")
                                 .ToDictionary(p => (string)p.Attribute("key"),
                                               p => (string)p.Attribute("value"));

            if (parameters.ContainsKey("BrandWebSite"))
            {
                var xmlBrandWebSite = parameters["BrandWebSite"];
                BrandWebsite.HRef = xmlBrandWebSite;
            }

            //Added by Dhruvik -- By Dhruvik -- Mantis Id:26991
            string SQL_String = "SELECT BrandConfig FROM sSetup.tOrgGroupMaster WHERE id = " + OrgGroupId;
            CommonFunctions cf = new CommonFunctions();
            DataSet ds = cf.GetDataset(SQL_String);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
            {
                SupportPhoneNoLabel.Text = ds.Tables[0].Rows[0][0].ToString();
            }
            else
            {
                if (parameters.ContainsKey("BrandSupport"))
                {
                    var xmlBrandSupport = parameters["BrandSupport"].Replace("||", "|");
                    SupportPhoneNoLabel.Text = xmlBrandSupport;
                    if (xmlBrandSupport == "")
                        SupportPhoneNoLabel.Visible = false;
                }
            }


            if (parameters.ContainsKey("BrandName"))
            {
                var xmlBrandName = parameters["BrandName"];
                ContacatusHyperLink.InnerText = xmlBrandName;
            }

            if (parameters.ContainsKey("BrandWebSite"))
            {
                var xmlBrandWebSite = parameters["BrandWebSite"];
                ContacatusHyperLink.HRef = xmlBrandWebSite;
            }

            if (parameters.ContainsKey("DevelopedBy"))
            {
                var xmlDevelopedByName = parameters["DevelopedBy"];
                DevelopedByHyperLink.InnerText = xmlDevelopedByName;
            }

            if (parameters.ContainsKey("DevelopedByWebSite"))
            {
                var xmlDevelopedByWebSite = parameters["DevelopedByWebSite"];
                DevelopedByHyperLink.HRef = xmlDevelopedByWebSite;
            }

            GetLicencedDetail();
            this.Page.Title = "Login";

            LogoImageButton.Attributes.Add("onclick", "javascript:LogoImageButtonClick()");

            string dir;
            dir = Server.MapPath("~/Content/" + OrgGroupId + "OrgGroup/Other");
            ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
            if (Directory.Exists(dir))
            {
                dir = Server.MapPath("~/Content/" + OrgGroupId + "OrgGroup/Other/LoginBg.jpg");
                if (File.Exists(dir))
                {
                    LoginBgImage.Src = Page.ResolveUrl("~/Content/" + OrgGroupId + "OrgGroup/Other/LoginBg.jpg");
                    mainDiv.Attributes["class"] = "maincontainer paddingZero";
                    rightcardImage.Attributes["class"] = "rightcard rightFullsizeSchoolImage";
                }
                else
                {
                    mainDiv.Attributes["class"] = mainDiv.Attributes["class"].Replace("paddingZero", "").Trim();
                    rightcardImage.Attributes["class"] = rightcardImage.Attributes["class"].Replace("rightFullsizeSchoolImage", "").Trim();
                }
            }
            else
            {
                mainDiv.Attributes["class"] = mainDiv.Attributes["class"].Replace("paddingZero", "").Trim();
                rightcardImage.Attributes["class"] = rightcardImage.Attributes["class"].Replace("rightFullsizeSchoolImage", "").Trim();
            }

            ForgotPasswordBox.Hide();

            ForgotPasswordBox.Click += new UserControls_ForgotPassword.OnButtonClick(SubmitButton_click);

            Form.DefaultButton = "loginButton";

            ErrorLabel.Text = String.Empty;
            Session.Clear();
            Session["VersionNumber"] = VersionNumber;
            userNameTextBox.Attributes.Add("onfocus", "this.select()");
            passwordTextBox.Attributes.Add("onfocus", "this.select()");
            string messageValue = Request.QueryString["NOL"] ?? "0";
            if (messageValue.Equals("0"))

                if (!messageValue.Equals("0"))
                {
                    switch (int.Parse(messageValue))
                    {
                        case -1:
                            ErrorLabel.Text = "Page expired - Session time out";
                            ErrorLabel.Visible = true;

                            break;

                        case -2:
                            ErrorLabel.Text = "Session inactivated due to multiple logins ";
                            ErrorLabel.Visible = true;

                            break;

                        case -201:
                            ErrorLabel.Text = "Licence Expired, Renew the Licence";
                            ErrorLabel.Visible = true;

                            break;

                        default:
                            ErrorLabel.Text = "Licence will Expire in other " + messageValue + " Day(s) , Renew the Licence";
                            ErrorLabel.Visible = true;
                            break;
                    }

                    if (!IsPostBack)
                    {
                        OrgDropDownList.Items.Add("- Select -");


                    }
                }


            if (!Page.IsPostBack)
            {
                hiddenMsg.Value = string.Empty;

                if (ConfigurationManager.AppSettings["HostedAs"] != null && ConfigurationManager.AppSettings["HostedAs"].ToString().ToLower() == "portal") // Offline,Online
                {
                    ContacatusHyperLink.Visible = false;
                    SupportPhoneNoLabel.Visible = false;
                    DevelopedByHyperLink.Visible = false;
                    ContactusDiv.Visible = false;
                    DevelopByDiv.Visible = false;
                }


                ListItem li1 = new ListItem("- Select -", "-1");

                BatchDropDownList.Items.Clear();
                BatchDropDownList.Items.Insert(0, li1);

                FillOrgDropDownList();

                if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null && Request.Cookies["OrgId"] != null && Request.Cookies["BatchId"] != null && Request.Cookies["StoreLocationId"] != null)
                {
                    userNameTextBox.Text = SecurityCryptography.DecryptString(Request.Cookies["UserName"].Value);
                    passwordTextBox.Attributes["value"] = SecurityCryptography.DecryptString(Request.Cookies["Password"].Value);
                    OrgDropDownList.SelectedValue = Request.Cookies["OrgId"].Value;
                    OrgDropDownList_OnSelectedIndexChanged(null, null);
                    BatchDropDownList.SelectedValue = Request.Cookies["BatchId"].Value;
                }
                else if (Request.Cookies["UserName"] != null && Request.Cookies["Password"] != null)
                {
                    userNameTextBox.Text = SecurityCryptography.DecryptString(Request.Cookies["UserName"].Value);
                    passwordTextBox.Attributes["value"] = SecurityCryptography.DecryptString(Request.Cookies["Password"].Value);
                    OrgDropDownList.Enabled = false;
                    BatchDropDownList.Enabled = false;
                }
                FillCapctha();
            }
            if (OrgGroupId != 0)
            {
                if (Convert.ToBoolean((ConfigurationHelper.GetUserConfigurationValueDirect(int.Parse(OrgGroupId.ToString()), 0, 0, "Security.IsCaptchaValidation"))) == true)
                {
                    Captchadiv.Visible = true;
                    captchacodediv.Visible = true;
                }
                else
                {
                    captchacodediv.Visible = false;
                    Captchadiv.Visible = false;
                }
            }
            OrgDropDownList.Focus();
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("Incorrect syntax near ')'"))
            {
                ErrorLabel.Text = "Your session expired, Please re-login to application";
                ErrorLabel.Visible = true;
            }
            else
            {
                ErrorLabel.Text = ex.Message;
                ErrorLabel.Visible = true;
            }
        }
    }

    public void GetLicencedDetail()
    {
        try
        {
            if (OrgGroupId != 0)
            {
                DataSet ds = new DataSet();
                string Sql = string.Empty;

                Sql = "select VersionNumber,ISNULL(IsNewVersion,0) AS IsNewVersion from sSystem.tDatabaseInfo";

                ds = CommonFunctionsServiceClient().GetDataset(Sql);

                if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                {
                    VersionNumber = ds.Tables[0].Rows[0]["VersionNumber"].ToString();
                    IsNewVersion = bool.Parse(ds.Tables[0].Rows[0]["IsNewVersion"].ToString());
                }
                else
                {
                    VersionNumber = string.Empty;
                    IsNewVersion = false;
                }

                ds = new DataSet();
                Sql = "SELECT Title,CRMLicenceNo FROM sSetup.tOrgGroupMaster WHERE Id = " + OrgGroupId;

                ds = CommonFunctionsServiceClient().GetDataset(Sql);

                if (ds != null && ds.Tables.Count > 0)
                {
                    if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                    {
                        LicenceNo.InnerText = ds.Tables[0].Rows[0]["CRMLicenceNo"].ToString();
                        LicenceTo.InnerText = ds.Tables[0].Rows[0]["Title"].ToString();
                        IPAddress.InnerText = GetVisitorIPAddress();
                        VersionNo.InnerText = VersionNumber;
                    }
                }
            }
        }
        catch (Exception)
        {

        }
    }

    void SubmitButton_click()
    {
        StatusInfo StatusInfoObject = new StatusInfo();
        StatusInfoObject = ForgotPasswordBox.Submit(int.Parse(OrgDropDownList.SelectedValue.ToString()));
        ErrorLabel.Text = StatusInfoObject.StatusText;
        if (StatusInfoObject.StatusId == 1)
        {
            ForgotPasswordBox.CheckStatus(1);
        }
        else if (StatusInfoObject.StatusId == -1)
        {
            ForgotPasswordBox.CheckStatus(-1);
        }
    }

    /// <summary>
    /// Handles the OK event of the ConfirmBox control.
    /// </summary>
    /// <param name="s">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ConfirmBox_OK(object s, EventArgs e)
    {
        int OrgId = int.Parse(OrgDropDownList.SelectedValue.ToString());
        int BatchId = int.Parse(BatchDropDownList.SelectedValue.ToString());
        string pwd = ViewState["pwd"].ToString() ?? string.Empty;
        LoginProcess(OrgId, pwd, BatchId);

    }
    /// <summary>
    /// Handles the Cancel event of the ConfirmBox control.
    /// </summary>
    /// <param name="s">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void ConfirmBox_Cancel(object s, EventArgs e)
    {
        OrgDropDownList.SelectedIndex = 0;
        userNameTextBox.Text = "";
        passwordTextBox.Text = "";
        OrgDropDownList.Focus();
    }
    /// <summary>
    /// Handles the Click event of the loginButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void loginButton_Click(object sender, EventArgs e)
    {
        try
        {
            //need to redirect to screen which is set into UserPreference only after login due to mantisid - 0028637
            Session["UserPreferenceWise"] = "UserPreferenceWise";
            int OrgId = int.Parse(OrgDropDownList.SelectedValue.ToString());
            int BatchId = int.Parse(BatchDropDownList.SelectedValue.ToString());

            if (userNameTextBox.Text != string.Empty && passwordTextBox.Text != string.Empty)
            {
                if (chkRememberMe.Checked)
                {
                    Response.Cookies["UserName"].Value = SecurityCryptography.EncryptString(userNameTextBox.Text.Trim());
                    Response.Cookies["Password"].Value = SecurityCryptography.EncryptString(passwordTextBox.Text.Trim());
                    Response.Cookies["OrgId"].Value = OrgDropDownList.SelectedValue.ToString();
                    Response.Cookies["BatchId"].Value = BatchDropDownList.SelectedValue.ToString();
                    Response.Cookies["StoreLocationId"].Value = (IdHelper.GetIntIdForOrg((int.Parse(OrgDropDownList.SelectedValue.ToString())), 1)).ToString();
                }
            }
            else if (userNameTextBox.Text == "SysSuperAdmin" && passwordTextBox.Text != string.Empty)
            {
                if (chkRememberMe.Checked)
                {
                    Response.Cookies["UserName"].Value = SecurityCryptography.EncryptString(userNameTextBox.Text.Trim());
                    Response.Cookies["Password"].Value = SecurityCryptography.EncryptString(passwordTextBox.Text.Trim());
                }
            }
            if (OrgDropDownList.SelectedIndex <= 0 && userNameTextBox.Text != "SysSuperAdmin")
            {
                ErrorLabel.Text = "Select Organization To Login";
                ErrorLabel.Visible = true;
                return;
            }
            else if (BatchDropDownList.SelectedIndex <= 0 && userNameTextBox.Text != "SysSuperAdmin")
            {
                ErrorLabel.Text = "Select Batch To Login";
                ErrorLabel.Visible = true;
                return;
            }
            else if (string.IsNullOrEmpty(userNameTextBox.Text))
            {
                ErrorLabel.Text = "Enter User Name";
                ErrorLabel.Visible = true;
                return;
            }
            else if (string.IsNullOrEmpty(passwordTextBox.Text))
            {
                ErrorLabel.Text = "Enter Password";
                ErrorLabel.Visible = true;
                return;
            }
            if (ConfigurationManager.AppSettings["ValidateDateFormat"].ToString().ToLower() == "true")
            {
                if (Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern != "dd/MM/yyyy")
                {
                    ErrorLabel.Text = "Check Date Fromat it should be in dd/MM/yyyy format on server";
                    ErrorLabel.Visible = true;
                    return;
                }
            }

            // Initialize FormsAuthentication (reads the configuration and gets
            // the cookie values and encryption keys for the given application)

            // for case sensitive
            if (userNameTextBox.Text.ToUpper() == "SYSSUPERADMIN" && userNameTextBox.Text != "SysSuperAdmin")
            {
                ErrorLabel.Text = "Enter valid Username.";
                ErrorLabel.Visible = true;
                return;
            }

            if (userNameTextBox.Text.ToUpper() == "SYSSUPERADMIN")
            {
                OrgId = 1;
            }
            FormsAuthentication.Initialize();
            hashedPassword = SecurityCryptography.EncryptString(passwordTextBox.Text.ToString());
            ViewState["pwd"] = hashedPassword;
            {
                if (AllowMoreSessions)
                {
                    if (OrgGroupId != 0)
                    {
                        if (Convert.ToBoolean((ConfigurationHelper.GetUserConfigurationValueDirect(int.Parse(OrgGroupId.ToString()), 0, 0, "Security.IsCaptchaValidation"))) == true)
                        {
                            if (string.IsNullOrEmpty(txtCaptcha.Text))
                            {
                                ErrorLabel.Text = "Enter captcha code.";
                                ErrorLabel.Visible = true;
                                txtCaptcha.Focus();
                                return;
                            }
                            else if (!string.IsNullOrEmpty(txtCaptcha.Text) && txtCaptcha.Text != imgCaptcha.Text)
                            {
                                ErrorLabel.Text = "Enter valid captcha code.";
                                ErrorLabel.Visible = true;
                                txtCaptcha.Focus();
                                return;
                            }
                        }
                    }

                    bool IsValid = LoginProcess(OrgId, hashedPassword, BatchId);
                    if (IsValid == true)
                    {
                        DataSet ds = new DataSet();
                        string Sql = string.Empty;
                        Sql = "Select * From sSecurity.tModulePermission Where ModuleId=2 AND OrgGroupId=" + SecuritySession.UserProfile.OrgGroupId;

                        ds = CommonFunctionsServiceClient().GetDataset(Sql);

                        if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                            Session["Alert"] = "True";
                        else
                            Session["Alert"] = "False";

                        if (SecuritySession.UserProfile.UserSourceTypeId != 2003 && !string.IsNullOrEmpty(ErpAPIUrl) && !string.IsNullOrEmpty(ErpOrgId.ToString()) && !string.IsNullOrEmpty(ErpUsername) && !string.IsNullOrEmpty(ErpPassword))
                            CRMUpdateAutoStopServiceDetails();
                        AddRegisteredUser();
                    }
                    return;
                }
                Boolean loggedIn = GetSecurityServiceClient().IsUserAlreadyLoggedIn(OrgId, userNameTextBox.Text, hashedPassword);
                if (loggedIn)
                {
                    LoginConfirmBox.Show("Currently you have one active logged in session. Click \"OK\" to login and will automatically terminate previous session & loses any unsaved data or \"Cancel\" to return to Login page");
                }
                else
                {
                    LoginProcess(OrgId, hashedPassword, BatchId);
                }
            }
        }
        catch (Exception ex)
        {
            HttpContext.Current.Session["ErrorMessage"] = ex.Message; //"Communication layer error - Service not found";
            Response.Redirect("~/Pages/Common/ErrorPages/CommonErrorPage.aspx", true);
        }
    }

    protected void ForgotPasswordLinkButton_Click(object o, EventArgs e)
    {
        if (OrgDropDownList.SelectedIndex > 0)
            ForgotPasswordBox.Show("");
        else
            ErrorLabel.Text = "Please Select Organization";
    }

    protected void FillOrgDropDownList()
    {
        int OrgId = 0;
        if (Request.QueryString["OrgId"] != null) OrgId = int.Parse(Request.QueryString["OrgId"].ToString());

        LoadDropDown LoadDropDownData = new LoadDropDown();
        CommonFunctions CommonFunctionsObject = new CommonFunctions();
        // Fills LoadDropDownData Object With Appropriate Values To Fill 
        LoadDropDownData.DropDownControlName = OrgDropDownList;
        LoadDropDownData.TableName = "[sSetup].[tOrganizationMaster]";
        LoadDropDownData.KeyFieldName = "Id";
        LoadDropDownData.FieldName = "DisplayTitle";
        if (OrgId == 0) LoadDropDownData.Condition = "IsObsolete=0 AND OrgGroupId = " + OrgGroupId;
        else LoadDropDownData.Condition = "IsObsolete=0 AND OrgGroupId = " + OrgGroupId + " AND Id=" + OrgId;
        LoadDropDownData.DisplayDefaultTextAsAll = false;
        LoadDropDownData.SortOrderObject = SortOrder.SortCustomAscending;
        LoadDropDownData.CustomSortField = "OrderIndex";
        LoadDropDownData.IsCacheEnabled = false;
        // Function To Load Drop Down List
        CommonFunctionsObject.LoadDropDownList(LoadDropDownData);
        //Changes for Mantis Id : 0032946 by Hemali
        string Sql_String = "SELECT DISTINCT Id,DisplayTitle,OrderIndex FROM [sSetup].[tOrganizationMaster] WHERE IsObsolete = 0 AND OrgGroupId = " + OrgGroupId + " ORDER BY OrderIndex ASC";
        CommonFunctions cf = new CommonFunctions();
        DataSet DS = cf.GetDataset(Sql_String);
        if (OrgId == 0)
        {
            if (DS != null && DS.Tables.Count > 0 && DS.Tables[0].Rows.Count > 0)
                OrgDropDownList.SelectedValue = DS.Tables[0].Rows[0]["Id"].ToString();
        }
        else
            OrgDropDownList.SelectedValue = OrgId.ToString();

        OrgDropDownList_OnSelectedIndexChanged(null, null);
    }

    protected void FillBatchDropDownList()
    {
        LoadDropDown LoadDropDownData = new LoadDropDown();
        CommonFunctions CommonFunctionsObject = new CommonFunctions();
        // Fills LoadDropDownData Object With Appropriate Values To Fill 
        LoadDropDownData.DropDownControlName = BatchDropDownList;
        LoadDropDownData.TableName = "[sSetup].[tBatchMaster]";
        LoadDropDownData.KeyFieldName = "Id";
        LoadDropDownData.FieldName = "Title";
        LoadDropDownData.Condition = "IsObsolete=0 AND IsHistory = 0 AND OrgId = " + OrgDropDownList.SelectedValue.ToString();
        LoadDropDownData.DisplayDefaultTextAsAll = false;
        LoadDropDownData.SortOrderObject = SortOrder.SortCustomDescending;
        LoadDropDownData.CustomSortField = "OrderIndex";
        LoadDropDownData.IsCacheEnabled = false;
        // Function To Load Drop Down List
        CommonFunctionsObject.LoadDropDownList(LoadDropDownData);
    }

    protected void OrgDropDownList_OnSelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (OrgDropDownList.SelectedIndex > 0)
            {
                FillBatchDropDownList();
                if (BatchDropDownList.Items.Count > 0) BatchDropDownList.SelectedIndex = 1;
            }
            else
            {
                ListItem li = new ListItem("- Select -", "-1");

                BatchDropDownList.Items.Clear();
                BatchDropDownList.Items.Insert(0, li);
            }
        }
        catch (Exception ex)
        {
        }
    }

    protected void userNameTextBox_TextChanged(object sender, EventArgs e)
    {
        try
        {
            if (userNameTextBox.Text == "SysSuperAdmin")
            {
                passwordTextBox.Focus();
                OrgDropDownList.SelectedIndex = 0;
                OrgDropDownList_OnSelectedIndexChanged(null, null);
                OrgDropDownList.Enabled = false;
                BatchDropDownList.Enabled = false;
            }
            else
            {
                OrgDropDownList.Enabled = true;
                BatchDropDownList.Enabled = true;
            }
        }
        catch (Exception ex)
        {
            if (ex.Message.Contains("database") == true)
                HttpContext.Current.Session["ErrorMessage"] = "Error connectiong database. Contact administrator."; //"Communication layer error - Service not found";
            else
                HttpContext.Current.Session["ErrorMessage"] = ex.Message; //"Communication layer error - Service not found";
            Response.Redirect("~/Pages/Common/ErrorPages/GlobalErrorPage.aspx");
        }
    }

    void SearchButton_Click(object sender, EventArgs e)
    {
        try
        {

        }
        catch
        {
            throw;
        }
    }

    #endregion

    #region Private Methods


    /// <summary>
    /// Logins the process.
    /// </summary>
    /// <param name="hashedPassword">The hashed password.</param>
    private bool LoginProcess(int orgId, String hashedPassword, int BatchId)
    {
        string HostAddress = GetVisitorIPAddress();
        //Added Local Ip Adreess By Foram -- Mantis Id: 0026378
        //string LocalAddress = GetVisitorIPAddress(true);
        string LocalAddress = GetVisitorIPAddress1(false);

        UserValidate UserValidateObj = new UserValidate();
        UserValidateObj.OrgId = orgId;
        UserValidateObj.UserTitle = userNameTextBox.Text;
        UserValidateObj.UserPassword = hashedPassword;
        UserValidateObj.HostAddress = HostAddress;
        UserValidateObj.SessionId = Session.SessionID;
        UserValidateObj.LocalAddress = LocalAddress;

        String userID, message;
        if (GetSecurityServiceClient().ValidateUser(UserValidateObj, out userID, out message))
        {
            String userData = String.Empty;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                                                    1, // Ticket version
                                                    userID, // Username to be associated with this ticket
                                                    DateTime.Now, // Date/time issued
                                                    DateTime.Now.AddMinutes(30), // Date/time to expire
                                                    false, // "true" for a persistent user cookie (could be a checkbox on form)
                                                    userData, // User-data (the roles from this user record in our database)
                                                    FormsAuthentication.FormsCookiePath); // Path cookie is valid for

            // Hash the cookie for transport over the wire
            string hash = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(
                                        FormsAuthentication.FormsCookieName, // Name of auth cookie (it's the name specified in web.config)
                                        hash); // Hashed ticket

            // Add the cookie to the list for outbound response
            Response.Cookies.Add(cookie);

            //Add to LoggedInUser Session
            bool StudentStopApplicationAccess = StudentStopApplication(Int64.Parse(userID));
            if (StudentStopApplicationAccess == false)
            {
                return false;
            }

            SetUserSession(orgId, Int64.Parse(userID), BatchId);
            //Generate Token for DBQueueBearerToken
            GenerateDBQueueToken(orgId);
            SetContextSession();
            ScreengroupSession();
            SetConfigurationSession();
            if (SecuritySession.UserProfile.UserSourceTypeId == 2003)
            {
                SetStudentProfile();
            }
            ClientReportCopy();

            //Add the Task Permission for User logged in
            SecurityHelper.SetTaskPermissionSession(SecuritySession.UserProfile.OrgGroupId, SecuritySession.UserProfile.UserId);
            // SetTaskPermissionSession(orgId,int.Parse(userID));


            // Redirect to requested URL, or homepage if no previous page requested
            //string returnUrl = Request.QueryString["ReturnUrl"];

            // Added rajendra 22 SEP 09
            Session["SessionID"] = Session.SessionID.ToString();
            string returnUrl = Page.ResolveUrl(@"~/Pages/Common/Default.aspx");

            // Checking Student limit For auto alert
            string HostedAs = ConfigurationManager.AppSettings["HostedAs"].ToString().ToLower();

            if (HostedAs == "online" || HostedAs == "portal")
            {
                if (SecuritySession.UserProfile.UserSourceTypeId != 2003)
                {
                    GetstudentAddLimit();
                }
            }

            // Don't call the FormsAuthentication.RedirectFromLoginPage since it could
            // replace the authentication ticket we just added...
            Response.Redirect(returnUrl, false);
            return true;
        }
        else
        {
            // Username and or password not found in our database...
            ErrorLabel.Text = message;
            ErrorLabel.Visible = true;
            return false;
        }
    }
    /// <summary>
    /// Get Student  Limit For Auto Alert
    /// </summary>
    protected void GetstudentAddLimit()
    {
        try
        {
            CommonFunctions cflog = new CommonFunctions();
            string sqllog = "SELECT TOP 1 1 FROM sSecurity.tUserLog WHERE OrgId=" + SecuritySession.UserProfile.OrgId + " AND  convert(date,LoggedInDateTime) >= convert(date,GetDate())";
            DataSet dscflog = cflog.GetDataset(sqllog);
            if (dscflog != null && dscflog.Tables[0].Rows.Count > 0) ;
            else
            {
                CommonFunctions cfVal = new CommonFunctions();

                string sqlval = "Select 1 as Result from [sSetup].[tOrgGroupSetting] Where Isnull(StudentCapReminderCount,0)>=3  AND  year(Isnull(LastStudentCapReminderDate,''))=datepart(year,sCommon.fGetDate()) AND datepart(month,Isnull(LastStudentCapReminderDate,'')) = datepart(month,sCommon.fGetDate())  AND OrgGroupId= '" + SecuritySession.UserProfile.OrgGroupId + "'";
                DataSet dsval = cfVal.GetDataset(sqlval);
                if (dsval != null && dsval.Tables[0].Rows.Count > 0)
                {
                    if (dsval.Tables[0].Rows[0]["Result"].ToString() == "1")
                    {
                        return;
                    }
                }
                EmailHelper EmailHelperObject = new EmailHelper();
                SMSHelper SMSHelperObject = new SMSHelper();
                StatusInfo StatusInfoData2 = new StatusInfo();
                StatusInfo StatusInfoData1 = new StatusInfo();
                int noofstudent = 0, Activestudent = 0;
                string sql_studentlimit = "Select ISNULL(NoOfStudent,0),Isnull(StudentCapReminderCount,0) AS StudentCapReminderCount,Isnull(LastStudentCapReminderDate,'') AS LastStudentCapReminderDate from " +
                                         "sSetup.tOrgGroupSetting Where OrgGroupId= '" + SecuritySession.UserProfile.OrgGroupId + "'";
                CommonFunctions cf = new CommonFunctions();
                DataSet dsstudentlimit = cf.GetDataset(sql_studentlimit);
                if (dsstudentlimit != null && dsstudentlimit.Tables[0].Rows.Count > 0)
                {
                    noofstudent = int.Parse(dsstudentlimit.Tables[0].Rows[0][0].ToString());
                }
                string sql_studentcount = "Select [sSetup].[fStudentCapGet](" + SecuritySession.UserProfile.OrgGroupBatchId + ")";
                CommonFunctions cfcount = new CommonFunctions();
                DataSet dsstudentcount = cfcount.GetDataset(sql_studentcount);

                if (dsstudentcount != null && dsstudentcount.Tables[0].Rows.Count > 0)
                {
                    Activestudent = int.Parse(dsstudentcount.Tables[0].Rows[0][0].ToString());
                }
                if (Activestudent >= noofstudent - 25)
                {
                    DataSet ds = new DataSet();
                    DataTable dt = new DataTable();
                    dt.Columns.Add("MobileNo", typeof(string));
                    dt.Columns.Add("MsgText", typeof(string));
                    dt.Columns.Add("Subject", typeof(string));
                    dt.Columns.Add("EmailId", typeof(string));
                    dt.Columns.Add("ReceiverSourceTypeId", typeof(string));
                    dt.Columns.Add("ReceiverSourceId", typeof(string));

                    if (Activestudent >= noofstudent)
                    {
                        //Changes for mantis Id :0035245
                        CommonFunctions cf1 = new CommonFunctions();
                        DataSet dsemail = new DataSet();
                        CustomerMessage CustomerMessageObj = new CustomerMessage();
                        CustomerMessageObj.OrgGroupId = SecuritySession.UserProfile.OrgGroupId;
                        CustomerMessageObj.ProductId = 1;

                        if (!string.IsNullOrEmpty(ErpUsername) && !string.IsNullOrEmpty(ErpPassword) && !string.IsNullOrEmpty(ErpOrgId.ToString()) && !string.IsNullOrEmpty(ErpAPIUrl))
                        {
                            string Token = ErpCommonFunctionService.GenerateToken(ErpUsername, ErpPassword, ErpOrgId, ErpAPIUrl);
                            string ApiUrl = ErpAPIUrl + "api/v1.0/CRMSyncWebService/GetCustomerMasterData";
                            string inputJson = (new JavaScriptSerializer()).Serialize(CustomerMessageObj);
                            ServicePointManager.Expect100Continue = true;
                            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11;
                            string inputd = ErpCommonFunctionService.EncryptAPIData_unicode(inputJson);
                            string webData = (new JavaScriptSerializer()).Serialize(inputd);
                            WebClient webclient = new WebClient();
                            webclient.Headers["Content-type"] = "application/json";
                            webclient.Headers.Add("Authorization", "Bearer " + Token);
                            webclient.Headers.Add("AuthenticationKey", "NetVidyalaya@123");
                            webclient.Headers.Add("OrgId", ErpOrgId.ToString());
                            webclient.Encoding = Encoding.UTF8;

                            string json = webclient.UploadString(ApiUrl, webData);
                            dynamic data = JObject.Parse(json);
                            if (data.statusMessage == "Success")
                            {
                                string Result = ErpCommonFunctionService.DecryptAPIString_unicode(JObject.Parse(json)["data"].ToString());
                                dsemail = JsonConvert.DeserializeObject<DataSet>(Result);
                            }
                            StringBuilder StringBuilder1 = new StringBuilder();
                            StringBuilder StringBuilder2 = new StringBuilder();

                            if (dsemail != null && dsemail.Tables[0].Rows.Count > 0)
                            {
                                StringBuilder1.Append("<br>Dear Customer,</br>");
                                StringBuilder1.Append("<br></br>");
                                StringBuilder1.Append("<br>Oraganization Name : <b> " + dsemail.Tables[0].Rows[0]["Title"].ToString() + ", </b></br>");
                                StringBuilder1.Append("<br></br>");
                                StringBuilder1.Append("<br>Greetings From Vidyalaya School Management Software.</br>");
                                StringBuilder1.Append("<br></br>");
                                StringBuilder1.Append("<br>This is to inform you that you have purchased " + noofstudent + " number of student subscription for Vidyalaya. You have crossed the subscription limit of the students that are " + Activestudent + ".</br>");
                                StringBuilder1.Append("<br></br>");
                                StringBuilder1.Append("<br>To Add more number of students (Min 25 Students) in Vidyalaya kindly purchase extra student Subscriptions, before the limit crossed for easy operation of Vidyalaya. Adding new student (Min 25 Students) would be granted on advance payment basis only.</br>");
                                StringBuilder1.Append("<br></br>");
                                StringBuilder1.Append("<br>Kindly contact Vidyalaya Account Department(75748 26468 / 90999 76034) for adding subscription and any other queries for the same.</br>");
                                StringBuilder1.Append("<br></br>");
                                StringBuilder1.Append("<br>Anticipate your co-operation on the same. Your continued patronage and suggestions are a vital part of our growth. And for that, we are most grateful.</br>");

                                StringBuilder2.Append("<br>Dear <b> " + dsemail.Tables[0].Rows[0]["Title"].ToString() + ", </b></br>");
                                StringBuilder2.Append("<br>No of student subscription for Vidyalaya is " + noofstudent + ". You are reaching at " + Activestudent + ".To Add more call  on 7574826468</br>");

                                DataRow dtrow = dt.NewRow();
                                dtrow["MobileNo"] = dsemail.Tables[0].Rows[0]["MobileNo"].ToString().Trim();
                                dtrow["MsgText"] = StringBuilder1.ToString();
                                dtrow["Subject"] = "NO of Student";
                                dtrow["EmailId"] = dsemail.Tables[0].Rows[0]["Email"].ToString();
                                dtrow["ReceiverSourceTypeId"] = 0;
                                dtrow["ReceiverSourceId"] = 0;
                                dt.Rows.Add(dtrow);
                                ds.Tables.Add(dt);
                                if (ds != null && ds.Tables.Count > 0)
                                {

                                    StatusInfoData2 = SendEmail(ds, "Custom", 29, SecuritySession.UserProfile.OrgId);
                                    ds.Tables[0].Rows[0]["MsgText"] = StringBuilder2.ToString();
                                    ds.AcceptChanges();
                                    StatusInfoData1 = SMSHelperObject.SendSMS(ds, "Custom", 29, SecuritySession.UserProfile.OrgId);
                                }
                                if (StatusInfoData2.StatusId == 1 && StatusInfoData1.StatusId == 1)
                                {
                                    ErrorLabel.Text = "Successfully Sent";
                                    UpdateStudentLimit(Int16.Parse(dsstudentlimit.Tables[0].Rows[0]["StudentCapReminderCount"].ToString()));
                                }
                                else if (StatusInfoData2.StatusId == 0)
                                {
                                    ErrorLabel.Text = "Error in Email sending - " + StatusInfoData2.StatusText;

                                }
                                else if (StatusInfoData1.StatusId == 0)
                                {
                                    ErrorLabel.Text = "Error in SMS sending - " + StatusInfoData2.StatusText;
                                }
                            }
                        }
                    }
                }
            }

        }
        catch (Exception ex)
        {
            ErrorLabel.Text = "Error on Sending Auto Alert";
            ErrorLabel.Visible = true;
            return;
        }
    }
    public StatusInfo SendEmail(DataSet ds1, string SourceEvent, Int32 EventId, Int32 OrgId)
    {
        StatusInfo StatusInfoData = new StatusInfo();
        StatusInfoData.StatusId = 0;
        CommonFunctions cfmailsettting = new CommonFunctions();
        string sql = "select * from sSystem.tSettingInfo";
        DataSet ds = cfmailsettting.GetDataset(sql);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            DataSet Statusds = new DataSet();
            Statusds = CreateEmailLog(ds1, 0, "", SourceEvent, EventId, OrgId);

            if (Statusds != null && Statusds.Tables.Count > 0 && Statusds.Tables[0].Rows.Count > 0 && Statusds.Tables[0].Rows[0]["Result"].ToString() == "1")
            {

                {
                    for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
                    {
                        if (ds1.Tables[0].Rows[i]["EmailId"] != DBNull.Value)
                        {
                            string to = ds1.Tables[0].Rows[i]["EmailId"].ToString();
                            string from = ds.Tables[0].Rows[0]["FromMail"].ToString();
                            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to);

                            string mailbody = ds1.Tables[0].Rows[i]["MsgText"].ToString();
                            message.Subject = ds1.Tables[0].Rows[i]["Subject"].ToString();
                            message.Body = mailbody;
                            message.BodyEncoding = Encoding.UTF8;
                            message.IsBodyHtml = true;

                            if (ds1.Tables[0].Columns.Contains("AttachMent") && ds1.Tables[0].Rows[i]["AttachMent"] != DBNull.Value)
                            {
                                System.Net.Mail.Attachment AttachFile = new System.Net.Mail.Attachment(ds1.Tables[0].Rows[i]["AttachMent"].ToString());
                                message.Attachments.Add(AttachFile);
                            }

                            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(ds.Tables[0].Rows[0]["SMTPServer"].ToString(), int.Parse(ds.Tables[0].Rows[0]["SMTPPort"].ToString()));
                            client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                            client.EnableSsl = true;
                            client.UseDefaultCredentials = false;
                            client.Credentials = new System.Net.NetworkCredential(ds.Tables[0].Rows[0]["APIKey"].ToString(), ds.Tables[0].Rows[0]["SecretKey"].ToString());
                            client.Send(message);
                        }
                    }

                    StatusInfoData.StatusId = 1;
                    StatusInfoData.StatusText = "Successfully Sent";
                }
            }
        }
        return StatusInfoData;
    }

    public DataSet CreateEmailLog(DataSet ds1, Int64 StatusId, string ResultMessage, string SourceEvent, Int32 EventId, Int32 OrgId)
    {
        DataSet Statusds = new DataSet();
        StringBuilder strBuilder = new StringBuilder();
        strBuilder.Append("<Table>");
        for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
        {
            if (ds1.Tables[0].Rows[i]["EmailId"].ToString() != string.Empty)
            {
                strBuilder.Append("<AlertLog>");
                strBuilder.Append("<ContactId>" + ds1.Tables[0].Rows[i]["EmailId"].ToString() + "</ContactId>");
                strBuilder.Append("<AlertMessage>" + ds1.Tables[0].Rows[i]["MsgText"].ToString() + "</AlertMessage>");
                strBuilder.Append("<AlertSubject>" + ds1.Tables[0].Rows[i]["Subject"].ToString() + "</AlertSubject>");
                strBuilder.Append("<StatusId>" + StatusId + "</StatusId>");
                strBuilder.Append("<ResultMessage>" + ResultMessage + "</ResultMessage>");
                strBuilder.Append("<SMSType>" + "" + "</SMSType>");
                strBuilder.Append("<SourceEvent>" + SourceEvent + "</SourceEvent>");
                strBuilder.Append("<EventId>" + EventId + "</EventId>");
                strBuilder.Append("<AlertModeId>" + 1 + "</AlertModeId>");
                strBuilder.Append("<CreatedUserId>" + SecuritySession.UserProfile.UserId + "</CreatedUserId>");
                strBuilder.Append("<ReceiverSourceTypeId>" + ds1.Tables[0].Rows[i]["ReceiverSourceTypeId"].ToString() + "</ReceiverSourceTypeId>");
                strBuilder.Append("<ReceiverSourceId>" + ds1.Tables[0].Rows[i]["ReceiverSourceId"].ToString() + "</ReceiverSourceId>");
                strBuilder.Append("</AlertLog>");
            }
        }
        strBuilder.Append("</Table>");
        SMSLog SMSLogData = new SMSLog();
        SMSLogData.XML = strBuilder.ToString();
        SMSLogData.OrgId = OrgId;
        SMSLogService SMSLogServiceClient = new SMSLogService();
        Statusds = SMSLogServiceClient.CreateSMSLog(SMSLogData);
        return Statusds;
    }

    public void UpdateStudentLimit(Int16 StudentCapReminderCount)
    {
        List<DataParameter> dp = new List<DataParameter>();
        DataParameter d;
        d = new DataParameter { Name = "@rOrgId", Value = SecuritySession.UserProfile.OrgId, DataType = System.Data.DbType.Int16 };
        dp.Add(d);
        d = new DataParameter { Name = "@rOrgGroupId", Value = SecuritySession.UserProfile.OrgGroupId, DataType = System.Data.DbType.Int32 };
        dp.Add(d);
        d = new DataParameter { Name = "@rStudentCapReminderCount", Value = StudentCapReminderCount, DataType = System.Data.DbType.Int16 };
        dp.Add(d);

        CommonFunctions cf = new CommonFunctions();
        DataSet ds = cf.GetDatasetFromSp("[sSetup].[ptOrgGroupSettingUpdateForStudentAlert]", dp);
    }
    public void AddRegisteredUser()
    {
        List<DataParameter> dp = new List<DataParameter>();
        DataParameter d;
        d = new DataParameter { Name = "@rOrgId", Value = SecuritySession.UserProfile.OrgId, DataType = System.Data.DbType.Int16 };
        dp.Add(d);
        d = new DataParameter { Name = "@rUserId", Value = SecuritySession.UserProfile.UserId, DataType = System.Data.DbType.Int64 };
        dp.Add(d);
        d = new DataParameter { Name = "@rUserSourceId", Value = SecuritySession.UserProfile.UserSourceId, DataType = System.Data.DbType.Int64 };
        dp.Add(d);
        d = new DataParameter { Name = "@rUserSourceTypeId", Value = SecuritySession.UserProfile.UserSourceTypeId, DataType = System.Data.DbType.Int16 };
        dp.Add(d);
        d = new DataParameter { Name = "@rDeviceToken", Value = TokenIdHiddenField.Value, DataType = System.Data.DbType.String };
        dp.Add(d);
        d = new DataParameter { Name = "@rOSTypeId", Value = 3, DataType = System.Data.DbType.Int16 };
        dp.Add(d);

        CommonFunctions cf = new CommonFunctions();
        DataSet ds = cf.GetDatasetFromSp("sCommunication.pRegisteredUsersAdd", dp);
    }

    public void GenerateDBQueueToken(int OrgId)
    {
        try
        {
            AlertQueueToken AlertQueueTokenObj = new AlertQueueToken();
            AlertQueueTokenObj.UserId = SecuritySession.UserProfile.UserId;
            AlertQueueTokenObj.OrgGroupId = SecuritySession.UserProfile.OrgGroupId;
            AlertQueueTokenObj.DisplayTitle = SecuritySession.UserProfile.DisplayTitle;
            AlertQueueTokenObj.BatchId = SecuritySession.UserProfile.BatchId;
            AlertQueueTokenObj.UserSourceId = SecuritySession.UserProfile.UserSourceId;
            AlertQueueTokenObj.OrgId = OrgId;

            AlertQueueNotification AlertQueueNotificationObj = new AlertQueueNotification();

            string AuthToken = string.Empty;
            string DBQueueLoginAuthToken = string.Empty;
            AuthToken = AlertQueueNotificationObj.GenerateToken(AlertQueueTokenObj, 0);

            if (!string.IsNullOrEmpty(AuthToken))
            {
                DBQueueLoginAuthToken = AlertQueueNotificationObj.CheckAuthLogin(AuthToken);
            }
        }
        catch (Exception ex)
        {
         
        }
    }

    /// <summary>
    /// method to get Client ip address
    /// </summary>
    /// <param name="GetLan"> set to true if want to get local(LAN) Connected ip address</param>
    /// <returns></returns>
    public static string GetVisitorIPAddress(bool GetLan = false)
    {
        string visitorIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (String.IsNullOrEmpty(visitorIPAddress))
            visitorIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

        if (string.IsNullOrEmpty(visitorIPAddress))
            visitorIPAddress = HttpContext.Current.Request.UserHostAddress;

        if (string.IsNullOrEmpty(visitorIPAddress) || visitorIPAddress.Trim() == "::1")
        {
            GetLan = true;
            visitorIPAddress = string.Empty;
        }

        if (GetLan && string.IsNullOrEmpty(visitorIPAddress))
        {
            //This is for Local(LAN) Connected ID Address
            string stringHostName = Dns.GetHostName();
            //Get Ip Host Entry
            IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
            //Get Ip Address From The Ip Host Entry Address List
            IPAddress[] arrIpAddress = ipHostEntries.AddressList;

            try
            {
                visitorIPAddress = arrIpAddress[arrIpAddress.Length - 2].ToString();
            }
            catch
            {
                try
                {
                    visitorIPAddress = arrIpAddress[0].ToString();
                }
                catch
                {
                    try
                    {
                        arrIpAddress = Dns.GetHostAddresses(stringHostName);
                        visitorIPAddress = arrIpAddress[0].ToString();
                    }
                    catch
                    {
                        visitorIPAddress = "127.0.0.1";
                    }
                }
            }

        }
        return visitorIPAddress;
    }

    public static string GetVisitorIPAddress1(bool GetLan = false)
    {
        try
        {
            string visitorIPAddress = " ";

            //This is for Local(LAN) Connected ID Address
            string stringHostName = Dns.GetHostName();
            //Get Ip Host Entry
            IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
            //Get Ip Address From The Ip Host Entry Address List
            IPAddress[] arrIpAddress = ipHostEntries.AddressList;

            try
            {
                visitorIPAddress = (GetLan ? arrIpAddress[arrIpAddress.Length - 2].ToString() : arrIpAddress[arrIpAddress.Length - 1].ToString());
            }
            catch
            {
                try
                {
                    visitorIPAddress = arrIpAddress[0].ToString();
                }
                catch
                {
                    try
                    {
                        arrIpAddress = Dns.GetHostAddresses(stringHostName);
                        visitorIPAddress = (GetLan ? arrIpAddress[arrIpAddress.Length - 2].ToString() : arrIpAddress[arrIpAddress.Length - 1].ToString());
                    }
                    catch
                    {
                        visitorIPAddress = "127.0.0.1";
                    }
                }
            }

            return visitorIPAddress;
        }
        catch (Exception ex)
        {
            return " ";
        }
    }

    /// <summary>
    /// Copy Client Reports.
    /// </summary>
    private void ClientReportCopy()
    {
        try
        {
            CommonFunctions cf = new CommonFunctions();
            if (IsNewVersion == true)
            {

                CopyDirectory(Server.MapPath(@"~\ReportClient"), Server.MapPath("~"), true);
                cf.GetDataset("UPDATE sSystem.tDatabaseinfo SET IsNewVersion = 0");
            }

        }
        catch (Exception)
        {
        }
    }
    private static bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting)
    {
        bool ret = true;
        try
        {
            SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
            DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";

            if (Directory.Exists(SourcePath))
            {
                if (Directory.Exists(DestinationPath) == false)
                    Directory.CreateDirectory(DestinationPath);

                foreach (string fls in Directory.GetFiles(SourcePath))
                {
                    FileInfo flinfo = new FileInfo(fls);
                    flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
                }

                foreach (string drs in Directory.GetDirectories(SourcePath))
                {
                    DirectoryInfo drinfo = new DirectoryInfo(drs);
                    if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false)
                        ret = false;
                }
            }
            else
            {
                ret = false;
            }
        }
        catch
        {
            ret = false;
        }
        return ret;
    }

    /// <summary>
    /// Sets the user session.
    /// </summary>
    /// <param name="userid">The userid.</param>
    private void SetUserSession(int orgId, Int64 userid, int BatchId)
    {
        LoggedInUser LoggedInUserData = new LoggedInUser();
        if (userid > IdHelper.GetBigIntIdForOrg(orgId, 2))
        {
            SecurityCommonFunctionService SecurityObject = new SecurityCommonFunctionService();
            LoggedInUserData = SecurityObject.GetLoggedInUser(orgId, userid, IdHelper.GetIntIdForOrg(orgId, 1), BatchId);

            LoggedInUserData.SessionId = Session.SessionID;
            if (LoggedInUserData.UserPhoto != null)
                LoggedInUserData.UserPhoto = ConvertThumbnail(LoggedInUserData.UserPhoto);

            SecurityObject.SaveBrowserSessionIdInUserTable(orgId, userid, Session.SessionID.ToString());
        }
        else
        {
            LoggedInUserData.DisplayTitle = userNameTextBox.Text;
            LoggedInUserData.UserId = userid;
            LoggedInUserData.OrgId = orgId;
        }
        if (string.IsNullOrEmpty(LoggedInUserData.MenuId.ToString()) || LoggedInUserData.MenuId == 0)
        {
            LoggedInUserData.HomePageUrl = "~/Pages/Common/HomePage.aspx";
        }
        else
        {
            LoggedInUserData.HomePageUrl = LoggedInUserData.HomePageUrl + "?MenuId=" + LoggedInUserData.MenuId.ToString();
        }
        SecuritySession.UserProfile = LoggedInUserData;

        if (LoggedInUserData.DisplayTitle == "SysSuperAdmin")
        {

            LoggedInUserData.OrgDisplayTitle = string.Empty;
            LoggedInUserData.BatchTitle = string.Empty;
            LoggedInUserData.HomePageUrl = "~/Pages/BaseFramework/Security/CreateOrganizationMaster.aspx";
        }
        else if (LoggedInUserData.RoleId == IdHelper.GetIntIdForOrg(LoggedInUserData.OrgGroupId, 22))
        {
            LoggedInUserData.HomePageUrl = "~/Pages/BaseFramework/MyDashBoard.aspx";
        }
        else if (LoggedInUserData.RoleId == IdHelper.GetIntIdForOrg(LoggedInUserData.OrgGroupId, 24))
        {
            LoggedInUserData.HomePageUrl = "~/Pages/BaseFramework/MyDashBoard.aspx";
        }
        else
        {
            LoggedInUserData.HomePageUrl = "~/Pages/BaseFramework/MyDashBoard.aspx";
        }

        //Changes for Mantis Id: 0030874
        if (PaymentResponse == 1)
        {
            LoggedInUserData.HomePageUrl = SecuritySession.UserProfile.UserSourceTypeId == 2003 ? "~/Pages/FeeManagement/MyFee.aspx" : "~/Pages/FeeManagement/PayStudentFee.aspx";
        }
        string LoginTitle = SecuritySession.UserProfile.UserId == 1 ? "SysSuperAdmin" : SecuritySession.UserProfile.LoginTitle;
        string[] LoginAuthorizationUserList = LoginAuthorizationUser.Split(',');
        for (int i = 0; i < LoginAuthorizationUserList.Count(); i++)
        {
            if (LoginAuthorizationUserList[i].ToString() == LoginTitle)
            {
                LoggedInUserData.HomePageUrl = "~/Pages/BaseFramework/Security/UserAuthentication.aspx";
            }
        }

        string SQL = "Select ISNULL(IsLock,0) FROM sSetup.tBatchMaster WHERE Id =" + SecuritySession.UserProfile.BatchId;
        CommonFunctions cf = new CommonFunctions();
        DataSet Ds = cf.GetDataset(SQL);
        if (Ds != null && Ds.Tables[0].Rows.Count > 0)
        {
            Boolean IsLock = Convert.ToBoolean(Ds.Tables[0].Rows[0][0].ToString());
            LoggedInUserData.IsBatchLock = IsLock;
        }
    }

    private void SetContextSession()
    {
        ContextData cd = new ContextData();
        SecuritySession.ContextData = cd;
        SecuritySession.ContextData.OrgId = SecuritySession.UserProfile.OrgId;
        SecuritySession.ContextData.BatchId = SecuritySession.UserProfile.BatchId;
        if (SecuritySession.UserProfile.UserSourceTypeId == 2003)
        {
            SecuritySession.ContextData.StudentId = SecuritySession.UserProfile.UserSourceId;
            SecuritySession.ContextData.AcademicId = SecuritySession.UserProfile.AcademicId;
        }
        else if (SecuritySession.UserProfile.UserSourceTypeId == 95)
        {
            SecuritySession.ContextData.EmployeeId = SecuritySession.UserProfile.UserSourceId;
        }

    }

    private void SetStudentProfile()
    {
        if (SecuritySession.UserProfile != null)
        {
            StudentProfile sp = new StudentProfile();
            SecuritySession.StudentProfile = sp;
            string SQL_String = "SELECT A.OrgId,BatchId,StudentId,A.Id AS AcademicId,SM.Code,A.RollNo,(FirstName +' '+MiddleName+' '+LastName)AS StudentName,SM.FirstName,SM.MiddleName," +
                                " SM.LastName,A.ClassId,A.DivisionId,(CM.DisplayTitle +'-'+ DM.DisplayTitle) AS ClassDivision,DPM.Id AS DepartmentId,DPM.DisplayTitle AS DepartmentName" +
                                " FROM sStudent.tAcademic A INNER JOIN sStudent.tStudentMaster SM ON A.StudentId=SM.Id	" +
                                " INNER JOIN sSetup.tClassMaster CM ON CM.Id=A.ClassId INNER JOIN sSetup.tDivisionMaster DM ON DM.Id = A.DivisionId" +
                                " INNER JOIN sSetup.tDepartmentMaster DPM ON DPM.Id = CM.DepartmentId" +
                                " WHERE A.Id=" + SecuritySession.UserProfile.AcademicId + " AND BatchId =" + SecuritySession.UserProfile.BatchId;
            CommonFunctions cf = new CommonFunctions();
            DataSet StudentProfileDs = cf.GetDataset(SQL_String);
            if (StudentProfileDs != null && StudentProfileDs.Tables[0].Rows.Count > 0)
            {
                SecuritySession.StudentProfile.OrgId = Convert.ToInt16(StudentProfileDs.Tables[0].Rows[0]["OrgId"].ToString());
                SecuritySession.StudentProfile.AcademicId = Convert.ToInt64(StudentProfileDs.Tables[0].Rows[0]["AcademicId"].ToString());
                SecuritySession.StudentProfile.StudentId = Convert.ToInt64(StudentProfileDs.Tables[0].Rows[0]["StudentId"].ToString());
                SecuritySession.StudentProfile.BatchId = Convert.ToInt32(StudentProfileDs.Tables[0].Rows[0]["BatchId"].ToString());
                SecuritySession.StudentProfile.ClassId = Convert.ToInt64(StudentProfileDs.Tables[0].Rows[0]["ClassId"].ToString());
                SecuritySession.StudentProfile.DivisionId = Convert.ToInt64(StudentProfileDs.Tables[0].Rows[0]["DivisionId"].ToString());
                SecuritySession.StudentProfile.ClassDivision = StudentProfileDs.Tables[0].Rows[0]["ClassDivision"].ToString();
                SecuritySession.StudentProfile.Code = StudentProfileDs.Tables[0].Rows[0]["Code"].ToString();
                SecuritySession.StudentProfile.RollNo = Convert.ToInt32(StudentProfileDs.Tables[0].Rows[0]["RollNo"].ToString());
                SecuritySession.StudentProfile.StudentName = StudentProfileDs.Tables[0].Rows[0]["StudentName"].ToString();
                SecuritySession.StudentProfile.FirstName = StudentProfileDs.Tables[0].Rows[0]["FirstName"].ToString();
                SecuritySession.StudentProfile.MiddleName = StudentProfileDs.Tables[0].Rows[0]["MiddleName"].ToString();
                SecuritySession.StudentProfile.LastName = StudentProfileDs.Tables[0].Rows[0]["LastName"].ToString();
                SecuritySession.StudentProfile.DepartmentId = Convert.ToInt64(StudentProfileDs.Tables[0].Rows[0]["DepartmentId"].ToString());
                SecuritySession.StudentProfile.DepartmentName = StudentProfileDs.Tables[0].Rows[0]["DepartmentName"].ToString();
            }
        }
    }
    private void ScreengroupSession()
    {
        if (SecuritySession.UserProfile != null)
        {
            List<ScreenGroupData> ScreenGroupDataDataList = new List<ScreenGroupData>();
            CommonMasterService ScreenGroupDataServiceClient = new CommonMasterService();
            ScreenGroupDataDataList = ScreenGroupDataServiceClient.GetAllScreenGroupDataList(0, SecuritySession.UserProfile.UserId);
            CommonSession.AllScreeenGroupListObject = ScreenGroupDataDataList;
        }
    }

    private void SetConfigurationSession()
    {
        if (SecuritySession.UserProfile != null)
        {
            SecurityCommonFunctionService SecurityObject = new SecurityCommonFunctionService();
            Dictionary<string, string> ConfigurationValue = SecurityObject.ConfigurationValueList(SecuritySession.UserProfile.OrgId, SecuritySession.UserProfile.UserId, SecuritySession.UserProfile.LocationId, SecuritySession.UserProfile.StoreLocationId, SecuritySession.UserProfile.OrgGroupId);
            SecuritySession.ConfigurationItemList = ConfigurationValue;
        }
    }

    private void FillCapctha()
    {
        try
        {
            Random random = new Random();
            string combination = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            StringBuilder captcha = new StringBuilder();
            for (int i = 0; i < 6; i++)
                captcha.Append(combination[random.Next(combination.Length)]);
            imgCaptcha.Text = captcha.ToString();
        }
        catch (Exception ex)
        {
            ErrorLabel.Text = "Erron On Loading";
            ErrorLabel.Visible = true;
        }
    }
    #endregion

    protected void ForgotPasswordLink_Click(object sender, EventArgs e)
    {
        try
        {
            if (OrgDropDownList.SelectedIndex <= 0)
            {
                ErrorLabel.Text = "Select Organization";
                ErrorLabel.Visible = true;
                OrgDropDownList.Focus();
                return;
            }
            Response.Redirect("~/Pages/BaseFramework/Security/ForgotPassword.aspx?OrgId=" + OrgDropDownList.SelectedValue + "");

        }
        catch (Exception ex)
        {
            ErrorLabel.Text = "Erron On Loading";
            ErrorLabel.Visible = true;
        }
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        try
        {

            FillCapctha();
        }
        catch (Exception ex)
        {
            ErrorLabel.Text = "Erron On Loading";
            ErrorLabel.Visible = true;
        }
    }
    protected void close_Click(object sender, EventArgs e)
    {
        myModal.Style.Add("display", "none");
    }
    private bool StudentStopApplication(Int64 userid)
    {
        CommonFunctions cf = new CommonFunctions();
        string GetUser = "SELECT SourceId AS UserSourceId FROM sSecurity.tUser WHERE SourceTypeId = 2003 AND Id=" + userid;
        DataSet GetUserDS = new DataSet();
        GetUserDS = cf.GetDataset(GetUser);
        if (GetUserDS != null && GetUserDS.Tables[0] != null && GetUserDS.Tables[0].Rows.Count > 0)
        {
            Int64 StudentId = Convert.ToInt64(GetUserDS.Tables[0].Rows[0]["UserSourceId"].ToString());
            string Query = "SELECT ISNULL(StudentCustomAlert,'') AS StudentCustomAlert,ISNULL(IsStopApplicationAccess,0) AS IsStopApplicationAccess FROM sStudent.tStudentCommunication WHERE StudentId =" + StudentId;
            DataSet ds = new DataSet();
            ds = cf.GetDataset(Query);
            if (ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                if (Convert.ToBoolean(ds.Tables[0].Rows[0]["IsStopApplicationAccess"]) == true)
                {
                    ErrorLabel.Text = ds.Tables[0].Rows[0]["StudentCustomAlert"].ToString();
                    ErrorLabel.Visible = true;
                    return false;
                }
            }
        }
        return true;
    }

    public void CRMUpdateAutoStopServiceDetails()
    {
        try
        {
            CommonFunctions cf = new CommonFunctions();
            //Change for offline CRM
            string ApiUrl = ErpAPIUrl + "api/v1.0/CRMSyncWebService/GetLicenseDetails";
            string Token = ErpCommonFunctionService.GenerateToken(ErpUsername, ErpPassword, ErpOrgId, ErpAPIUrl);
            var input = new
            {
                OrgGroupId = OrgGroupId,
                ProductId = 1
            };

            string inputJson = (new JavaScriptSerializer()).Serialize(input);

            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11;
            string inputd = EncryptAPIData_unicode(inputJson);
            string webData = (new JavaScriptSerializer()).Serialize(inputd);
            WebClient webclient = new WebClient();
            webclient.Headers["Content-type"] = "application/json";
            webclient.Headers.Add("Authorization", "Bearer " + Token);
            webclient.Headers.Add("AuthenticationKey", "NetVidyalaya@123");
            webclient.Headers.Add("OrgId", ErpOrgId.ToString());
            webclient.Encoding = Encoding.UTF8;

            string json = webclient.UploadString(ApiUrl, webData);
            dynamic data = JObject.Parse(json);

            if (data.statusMessage == "Success")
            {
                string Result = DecryptAPIString_unicode(JObject.Parse(json)["data"].ToString());
                DataSet DS = JsonConvert.DeserializeObject<DataSet>(Result);
                if (DS != null && DS.Tables.Count > 0)
                {
                    if (DS.Tables["MyTable"].Rows.Count > 0)
                    {
                        if (string.IsNullOrEmpty(DS.Tables["MyTable"].Rows[0]["ServiceStopDate"].ToString()) && string.IsNullOrEmpty(DS.Tables["MyTable"].Rows[0]["PaymentDueDate"].ToString()))
                        {
                            string ServiceStopRemark = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["ServiceStopRemark"].ToString());
                            string IsStopServiceReminder = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["IsStopServiceReminder"].ToString());
                            string PaymentReminderRemark = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["PaymentReminderRemark"].ToString());
                            string IsPaymentReminder = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["IsPaymentReminder"].ToString());
                            string IsAutoStopService = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["IsAutoStopService"].ToString());

                            string OrgGroupSettingSQLString = "Update sSetup.tOrgGroupSetting SET PaymentDueDate= NULL ,IsPaymentReminder='" + IsPaymentReminder + "',PaymentReminderRemark='" + PaymentReminderRemark.Replace("'", "''") + "'," +
                               " IsStopServiceReminder='" + IsStopServiceReminder + "',ServiceStopRemark='" + ServiceStopRemark.Replace("'", "''") + "', " +
                               " ServiceStopDate= NULL, IsAutoStopService= '" + IsAutoStopService + "',UpdatedDate = sCommon.fGetDate() WHERE OrgGroupId=" + OrgGroupId;

                            string Check = "IF EXISTS (SELECT 1 FROM sSetup.tOrgGroupSetting WHERE OrgGroupId=" + OrgGroupId + ") BEGIN " + OrgGroupSettingSQLString + " END ELSE BEGIN " +
                                " INSERT INTO sSetup.tOrgGroupSetting (OrgGroupId,PaymentDueDate,IsPaymentReminder,PaymentReminderRemark,IsStopServiceReminder,ServiceStopRemark,ServiceStopDate,IsAutoStopService,UpdatedDate) VALUES " +
                                " (" + OrgGroupId + ",NULL,'" + IsPaymentReminder + "','" + PaymentReminderRemark.Replace("'", "''") + "','" + IsStopServiceReminder + "','" + ServiceStopRemark.Replace("'", "''") + "',NULL,'" + IsAutoStopService + "',sCommon.fGetDate()) END";

                            cf.GetDataset(Check);
                        }
                        else if (string.IsNullOrEmpty(DS.Tables["MyTable"].Rows[0]["ServiceStopDate"].ToString()))
                        {
                            string ServiceStopRemark = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["ServiceStopRemark"].ToString());
                            string IsStopServiceReminder = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["IsStopServiceReminder"].ToString());
                            string PaymentDueDate = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["PaymentDueDate"].ToString());
                            string PaymentReminderRemark = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["PaymentReminderRemark"].ToString());
                            string IsPaymentReminder = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["IsPaymentReminder"].ToString());
                            string IsAutoStopService = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["IsAutoStopService"].ToString());

                            string OrgGroupSettingSQLString = "Update sSetup.tOrgGroupSetting SET PaymentDueDate= '" + PaymentDueDate + "' ,IsPaymentReminder='" + IsPaymentReminder + "',PaymentReminderRemark='" + PaymentReminderRemark.Replace("'", "''") + "'," +
                               " IsStopServiceReminder='" + IsStopServiceReminder + "',ServiceStopRemark='" + ServiceStopRemark.Replace("'", "''") + "', " +
                               " ServiceStopDate= NULL, IsAutoStopService= '" + IsAutoStopService + "',UpdatedDate = sCommon.fGetDate() WHERE OrgGroupId=" + OrgGroupId;

                            string Check = "IF EXISTS (SELECT 1 FROM sSetup.tOrgGroupSetting WHERE OrgGroupId=" + OrgGroupId + ") BEGIN " + OrgGroupSettingSQLString + " END ELSE BEGIN " +
                               " INSERT INTO sSetup.tOrgGroupSetting (OrgGroupId,PaymentDueDate,IsPaymentReminder,PaymentReminderRemark,IsStopServiceReminder,ServiceStopRemark,ServiceStopDate,IsAutoStopService,UpdatedDate) VALUES " +
                               " (" + OrgGroupId + ",'" + PaymentDueDate + "','" + IsPaymentReminder + "','" + PaymentReminderRemark.Replace("'", "''") + "','" + IsStopServiceReminder + "','" + ServiceStopRemark.Replace("'", "''") + "',NULL,'" + IsAutoStopService + "',sCommon.fGetDate()) END";

                            cf.GetDataset(Check);
                        }
                        else if (string.IsNullOrEmpty(DS.Tables["MyTable"].Rows[0]["PaymentDueDate"].ToString()))
                        {
                            string ServiceStopDate = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["ServiceStopDate"].ToString());
                            string ServiceStopRemark = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["ServiceStopRemark"].ToString());
                            string IsStopServiceReminder = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["IsStopServiceReminder"].ToString());
                            string PaymentReminderRemark = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["PaymentReminderRemark"].ToString());
                            string IsPaymentReminder = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["IsPaymentReminder"].ToString());
                            string IsAutoStopService = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["IsAutoStopService"].ToString());

                            string OrgGroupSettingSQLString = "Update sSetup.tOrgGroupSetting SET PaymentDueDate= NULL ,IsPaymentReminder='" + IsPaymentReminder + "',PaymentReminderRemark='" + PaymentReminderRemark.Replace("'", "''") + "'," +
                               " IsStopServiceReminder='" + IsStopServiceReminder + "',ServiceStopRemark='" + ServiceStopRemark.Replace("'", "''") + "', " +
                               " ServiceStopDate= '" + ServiceStopDate + "', IsAutoStopService= '" + IsAutoStopService + "',UpdatedDate = sCommon.fGetDate() WHERE OrgGroupId=" + OrgGroupId;

                            string Check = "IF EXISTS (SELECT 1 FROM sSetup.tOrgGroupSetting WHERE OrgGroupId=" + OrgGroupId + ") BEGIN " + OrgGroupSettingSQLString + " END ELSE BEGIN " +
                               " INSERT INTO sSetup.tOrgGroupSetting (OrgGroupId,PaymentDueDate,IsPaymentReminder,PaymentReminderRemark,IsStopServiceReminder,ServiceStopRemark,ServiceStopDate,IsAutoStopService,UpdatedDate) VALUES " +
                               " (" + OrgGroupId + ",NULL,'" + IsPaymentReminder + "','" + PaymentReminderRemark.Replace("'", "''") + "','" + IsStopServiceReminder + "','" + ServiceStopRemark.Replace("'", "''") + "','" + ServiceStopDate + "','" + IsAutoStopService + "',sCommon.fGetDate()) END";

                            cf.GetDataset(Check);
                        }
                        else
                        {
                            string ServiceStopDate = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["ServiceStopDate"].ToString());
                            string ServiceStopRemark = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["ServiceStopRemark"].ToString());
                            string PaymentDueDate = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["PaymentDueDate"].ToString());
                            string IsStopServiceReminder = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["IsStopServiceReminder"].ToString());
                            string PaymentReminderRemark = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["PaymentReminderRemark"].ToString());
                            string IsPaymentReminder = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["IsPaymentReminder"].ToString());
                            string IsAutoStopService = SecurityCryptography.DecryptString(DS.Tables["MyTable"].Rows[0]["IsAutoStopService"].ToString());


                            string OrgGroupSettingSQLString = "Update sSetup.tOrgGroupSetting SET PaymentDueDate= '" + PaymentDueDate + "' ,IsPaymentReminder='" + IsPaymentReminder + "',PaymentReminderRemark='" + PaymentReminderRemark.Replace("'", "''") + "'," +
                               " IsStopServiceReminder='" + IsStopServiceReminder + "',ServiceStopRemark='" + ServiceStopRemark.Replace("'", "''") + "', " +
                               " ServiceStopDate= '" + ServiceStopDate + "', IsAutoStopService= '" + IsAutoStopService + "',UpdatedDate = sCommon.fGetDate() WHERE OrgGroupId=" + OrgGroupId;

                            string Check = "IF EXISTS (SELECT 1 FROM sSetup.tOrgGroupSetting WHERE OrgGroupId=" + OrgGroupId + ") BEGIN " + OrgGroupSettingSQLString + " END ELSE BEGIN " +
                               " INSERT INTO sSetup.tOrgGroupSetting (OrgGroupId,PaymentDueDate,IsPaymentReminder,PaymentReminderRemark,IsStopServiceReminder,ServiceStopRemark,ServiceStopDate,IsAutoStopService,UpdatedDate) VALUES " +
                               " (" + OrgGroupId + ",'" + PaymentDueDate + "','" + IsPaymentReminder + "','" + PaymentReminderRemark.Replace("'", "''") + "','" + IsStopServiceReminder + "','" + ServiceStopRemark.Replace("'", "''") + "','" + ServiceStopDate + "','" + IsAutoStopService + "',sCommon.fGetDate()) END";

                            cf.GetDataset(Check);
                        }
                    }
                    if (DS.Tables["StudentData"].Rows.Count > 0)
                    {
                        int NoOfStudent = Convert.ToInt32(DS.Tables["StudentData"].Rows[0]["NoOfStudent"].ToString());
                        int StudentExtraCap = Convert.ToInt32(DS.Tables["StudentData"].Rows[0]["StudentExtraCap"].ToString());
                        string ExtraCapValidUptoDate = Convert.ToDateTime(DS.Tables["StudentData"].Rows[0]["ExtraCapValidUptoDate"].ToString()).ToString("yyyy/MM/dd");

                        string OrgGroupSettingSQLString = "Update sSetup.tOrgGroupSetting SET NoOfStudent=" + NoOfStudent + ",StudentExtraCap=" + StudentExtraCap + "," +
                              " ExtraCapValidUptoDate='" + ExtraCapValidUptoDate + "',UpdatedDate = sCommon.fGetDate() WHERE OrgGroupId=" + OrgGroupId;

                        string Check = "IF EXISTS (SELECT 1 FROM sSetup.tOrgGroupSetting WHERE OrgGroupId=" + OrgGroupId + ") BEGIN " + OrgGroupSettingSQLString + " END ";
                        cf.GetDataset(Check);
                    }
                }
            }

        }
        catch (Exception ex)
        {

        }
    }
    #region Convert Thumbnail
    public byte[] ConvertThumbnail(byte[] Thumbnail)
    {
        byte[] ReturnedThumbnail = Thumbnail;

        using (MemoryStream StartMemoryStream = new MemoryStream(),
                                    NewMemoryStream = new MemoryStream())
        {
            // write the string to the stream  
            StartMemoryStream.Write(ReturnedThumbnail, 0, ReturnedThumbnail.Length);

            // create the start Bitmap from the MemoryStream that contains the image  
            if (ReturnedThumbnail.Length > 4)
            {

                Bitmap startBitmap = new Bitmap(StartMemoryStream);

                // set thumbnail height and width proportional to the original image.  
                int newHeight;
                int newWidth;
                double HW_ratio;
                if (startBitmap.Height > startBitmap.Width)
                {
                    newHeight = 95;
                    HW_ratio = (double)((double)95 / (double)startBitmap.Height);
                    newWidth = (int)(HW_ratio * (double)startBitmap.Width);
                }
                else
                {
                    newWidth = 95;
                    HW_ratio = (double)((double)95 / (double)startBitmap.Width);
                    newHeight = (int)(HW_ratio * (double)startBitmap.Height);
                }

                // create a new Bitmap with dimensions for the thumbnail.  
                Bitmap newBitmap = new Bitmap(newWidth, newHeight);

                // Copy the image from the START Bitmap into the NEW Bitmap.  
                // This will create a thumnail size of the same image.  
                newBitmap = ResizeImage(startBitmap, newWidth, newHeight);

                // Save this image to the specified stream in the specified format.  
                newBitmap.Save(NewMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);

                // Fill the byte[] for the thumbnail from the new MemoryStream.  
                ReturnedThumbnail = NewMemoryStream.ToArray();
            }
        }
        return ReturnedThumbnail;
    }

    private static Bitmap ResizeImage(Bitmap image, int width, int height)
    {
        Bitmap resizedImage = new Bitmap(width, height);
        using (Graphics gfx = Graphics.FromImage(resizedImage))
        {
            gfx.DrawImage(image, new Rectangle(0, 0, width, height),
                new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
        }
        return resizedImage;
    }
    #endregion
    [System.Web.Services.WebMethod]
    public static string GetConfigValues(string OrgGroupId)
    {
        DataTable dt = new DataTable();
        List<DataParameter> dp = new List<DataParameter>();
        DataParameter d;
        d = new DataParameter { Name = "@rOrgGroupId", Value = int.Parse(OrgGroupId), DataType = System.Data.DbType.Int32 };
        dp.Add(d);
        CommonFunctions cf = new CommonFunctions();
        DataSet ds = cf.GetDatasetFromSp("[sConfig].[pWebNotificationConfigGet]", dp);
        dt = ds.Tables[0];

        return DataTableToJSON(dt);
    }
    public static string DataTableToJSON(DataTable table)
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row;
        foreach (DataRow dr in table.Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn col in table.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }
            rows.Add(row);
        }
        serializer.MaxJsonLength = Int32.MaxValue;
        return serializer.Serialize(rows).Replace("[", "").Replace("]", "");
    }

    private string GenerateToken()
    {
        string Token = string.Empty;
        string TokenUrl = "https://erpnew.onlinevidyalaya.net/api/v1.0/Token/RequestToken";
        //string TokenUrl = "https://localhost:44375/api/v1.0/Token/RequestToken";

        var httpClientHandler = new HttpClientHandler();
        ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(delegate { return true; });
        WebClient client = new WebClient();
        object input = new
        {
            Username = ErpUsername.ToString(),
            Password = ErpPassword.ToString(),
            orgid = ErpOrgId.ToString()
        };
        string inputData = (new JavaScriptSerializer()).Serialize(input);
        client.Headers["Content-type"] = "application/json";
        client.Headers.Add("AuthenticationKey", "/rZppk3krl2GewNPNLUAuYGZcrTwXQ52rGKz6zJuTrs=");
        client.Headers.Add("OrgId", ErpOrgId.ToString());
        client.Encoding = Encoding.UTF8;
        string Tokenjson = client.UploadString(TokenUrl, inputData);
        Token = Tokenjson.ToString();
        return Token;
    }

    private static string EncryptAPIData_unicode(string strData)
    {
        byte[] key = Encoding.UTF8.GetBytes("wjmJIY2zScly1bctD26fDIN6nUJ4Qavn");
        byte[] iv = Encoding.Default.GetBytes("wjmJIY2zScly1bct");
        Aes encryptor = Aes.Create();
        encryptor.Mode = CipherMode.CBC;

        //// Set key and IV
        byte[] aesKey = new byte[32];
        Array.Copy(key, 0, aesKey, 0, 32);
        encryptor.Key = aesKey;
        encryptor.IV = iv;
        MemoryStream memoryStream = new MemoryStream();
        ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);
        byte[] plainBytes = Encoding.UTF8.GetBytes(strData);
        cryptoStream.Write(plainBytes, 0, plainBytes.Length);
        cryptoStream.FlushFinalBlock();
        byte[] cipherBytes = memoryStream.ToArray();
        memoryStream.Close();
        cryptoStream.Close();
        string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
        return cipherText;
    }

    public static string DecryptAPIString_unicode(string cipherText)
    {
        //SHA256 mySHA256 = SHA256Managed.Create();
        //byte[] key = mySHA256.ComputeHash(Encoding.Unicode.GetBytes("wjmJIY2zScly1bctD26fDIN6nUJ4Qavn"));
        byte[] key = Encoding.UTF8.GetBytes("wjmJIY2zScly1bctD26fDIN6nUJ4Qavn");
        byte[] iv = Encoding.Default.GetBytes("wjmJIY2zScly1bct");

        Aes encryptor = Aes.Create();
        encryptor.Mode = CipherMode.CBC;

        // Set key and IV
        byte[] aesKey = new byte[32];
        Array.Copy(key, 0, aesKey, 0, 32);
        encryptor.Key = aesKey;
        encryptor.IV = iv;
        MemoryStream memoryStream = new MemoryStream();
        ICryptoTransform aesDecryptor = encryptor.CreateDecryptor();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write);
        string plainText = String.Empty;

        try
        {
            byte[] cipherBytes = Convert.FromBase64String(cipherText);
            cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);
            cryptoStream.FlushFinalBlock();
            byte[] plainBytes = memoryStream.ToArray();
            plainText = Encoding.UTF8.GetString(plainBytes, 0, plainBytes.Length);
        }
        finally
        {
            memoryStream.Close();
            cryptoStream.Close();
        }
        return plainText;
    }
}
