Single Sign in using B2C

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Default" EnableEventValidation="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <telerik:RadStyleSheetManager ID="RadStyleSheetManager1" runat="server" />
    <style type="text/css">
        .signClass {
            position: absolute;
            height: 40px;
            top: 50px;
            right: 50px;
            background-color: #257525;
            color: #FFF;
            padding: 10px 20px;
            font-weight: 900;
            font-family: Arial;
            border-bottom: 1px solid #FFF;
            letter-spacing: 2px;
            text-transform: uppercase;
        }


            .signClass:hover {
                box-shadow: 2px 2px 3px 3px rgba(255, 255, 255, 0.25);
            }
    </style>
   <%-- <script src="js/modernizr.js" type="text/javascript"></script>--%>
    <link href="css/normalize.min.css" rel="stylesheet" />
    <link href="css/bootstrap.min.css" rel="stylesheet" />
    <link href="css/style.css" rel="stylesheet" />     <script src="js/jquery.min.js" type="text/javascript"></script>
  <%-- For Call hidden button in javascript (Background re Asp Button click Event ku Call Kariba)--%>
     <script type="text/javascript">
        $(document).ready(function () {
         
            $("#div_partner").click(function () {
                __doPostBack('btn_postHidden', 'OnClick');
            });
            $("#div_client").click(function () {
                __doPostBack('btn_clientpostHidden', 'OnClick');
            });
        });
    </script>
  <%-- ----------------End------------------------%>

</head>
<body>
    <form id="form1" runat="server">
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
            <Scripts>
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
                <asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
            </Scripts>
        </telerik:RadScriptManager>
        <script type="text/javascript">
            //Put your JavaScript code here.
        </script>
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        </telerik:RadAjaxManager>
        <div>
            <div class="carousel slide carousel-fade" data-ride="carousel">

                <!-- Wrapper for slides -->
                <div class="carousel-inner" role="listbox">
                    <div id="div_background1" class="item active" runat="server">
                    </div>
                    <div id="div_background2" class="item" runat="server">
                    </div>
                    <div id="div_background3" class="item" runat="server">
                    </div>
                </div>
            </div>


            <div class="logo">
                <img id="img_logo" runat="server" src="~/images/logo.png" style="height: 80px" alt="" />
                <asp:Label ID="lblname" runat="server" ></asp:Label>
            </div>
            <asp:Button ID="btnAdmin" runat="server" Text="Swash Admin" OnClick="btnAdmin_Click" />
            <div class="container top-pad">


                <div class="row">
                    <div class="col-sm-6">
                       
                        <div class="panel orange-tile" id="div_client">
                            <div class="panel-body">
                                <div align="center">
                                    <img src="images/myportal-icon.png" alt="" class="Panel-Img" /></div>
                                <h1 align="center">My Portal</h1>
                               <%-- <div class="arrow-right pull-right"></div>--%>
                               <%-- <asp:Button ID="btn_signinPortal" runat="server" Text="Go" CssClass="btn btn-primary btnpad pull-right" OnClick="btn_signinPortal_Click" />
                                <asp:Button ID="btn_signupPortal" runat="server" Text="SignUp" CssClass="btn btn-primary btnpad pull-right" OnClick="btn_signupPortal_Click" />--%>

                            </div>
                        </div>
                           
                    </div>
                    <div class="col-sm-6">
                     
                        <div class="panel yellow-tile" id="div_partner" >
                            <div class="panel-body">
                                <div align="center">
                                    <img src="images/mypartner-icon.png" alt="" class="Panel-Img" />

                                    <asp:Button id="btn_postHidden" runat="server" OnClick="btn_postHidden_Click" Visible="false" ClientIDMode = "static"/>
                                    <asp:Button id="btn_clientpostHidden" runat="server" OnClick="btn_clientpostHidden_Click" Visible="false" ClientIDMode = "static"/>
                                </div>
                                <h1 align="center">My Partner</h1>

                            <%--<div class="arrow-rightwo pull-right"></div>--%>
                                <%--    <asp:Button ID="btn_signin" runat="server" Text="Go" CssClass="btn btn-danger btnpad pull-right" OnClick="btn_signin_Click" />
                                <asp:Button ID="btn_signup" runat="server" Text="SignUp" CssClass="btn btn-danger btnpad pull-right" OnClick="btn_signup_Click" />--%>

                            </div>
                        </div>


                         
                     
                    </div>
                </div>

           
            </div>
     
          <%--  <script src="js/bootstrap.min.js" type="text/javascript"></script>
            <script src="js/index.js" type="text/javascript"></script>--%>


        </div>
    </form>
</body>
</html>
========================
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Newtonsoft.Json;
using Telerik.Web.UI;
using Microsoft.Owin.Security;
using KenAdmin.App_Start;

using System.Security.Claims;
using System.Web.Http;
using System.Threading;



using System.Linq;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using BusinessEntities;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
using Newtonsoft.Json.Linq;
using KenAdmin.Objects;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System.IO;
using Microsoft.WindowsAzure;

public partial class Default : System.Web.UI.Page
{
    #region Variable & Object or Reference Declare Section
    public List<Master_Login_User> LoginList1 = new List<Master_Login_User>();
    public List<Master_Login_History> loginhistory = new List<Master_Login_History>();
    public List<Master_User_Registration> MasterUserRegdList = new List<Master_User_Registration>();
    public List<Master_Azure_StaticReturnValue> MasterAzureStaticList = new List<Master_Azure_StaticReturnValue>();
    public List<Master_Azure_DynamicReturnValue> MasterAzureDynamicList = new List<Master_Azure_DynamicReturnValue>();
    public List<Master_Admin_Login_Lookup> MasterAdminLoginLookUp = new List<Master_Admin_Login_Lookup>();
    public List<Master_Login_Version> MasterLoginVersion = new List<Master_Login_Version>();
    public List<Master_Device_Type> MasterDeviceType = new List<Master_Device_Type>();
    public List<Master_Device_Registration> MasterDeviceRegistration = new List<Master_Device_Registration>();
    public List<Master_Login_History> MasterLoginHistory = new List<Master_Login_History>();
    public List<Master_KenPartner> MasterKenPartner = new List<Master_KenPartner>();
    public List<Master_ERPClient_Member> MasterERPClientMember = new List<Master_ERPClient_Member>();
    public List<Client_Registration> ClientRegistration = new List<Client_Registration>();
    public List<getid> getIDD = new List<getid>();
    public List<KP_Application> KPApplication = new List<KP_Application>();



    List<Master_User_Registration> LoginList = null;

    HttpClient client = new HttpClient();

    #endregion


    #region KenCommerce Registration Database
    HttpClient client1 = new HttpClient();
    List<Master_Login_Users> Login_UserList1 = null;

    public List<Master_Login_Users> gETMaster_Login_User1 = new List<Master_Login_Users>();


    public class Master_Login_Users
    {
        public int Login_User_ID
        {
            get;
            set;
        }
        public Nullable<int> Cloud_Login_ID
        {
            get;
            set;
        }
        public string Login_User_Type
        {
            get;
            set;
        }
        public string Login_EmailId
        {
            get;
            set;
        }
        public string Login_Username
        {
            get;
            set;
        }
        public string Login_Password
        {
            get;
            set;
        }
        public string Login_MobileNo
        {
            get;
            set;
        }
        public Nullable<bool> Is_KeepSignIn
        {
            get;
            set;
        }
        public Nullable<System.DateTime> InsertedOn
        {
            get;
            set;
        }
        public Nullable<int> InsertedBy
        {
            get;
            set;
        }
        public Nullable<System.DateTime> LastModifiedOn
        {
            get;
            set;
        }
        public Nullable<int> LastModifiedBy
        {
            get;
            set;
        }
        public Nullable<bool> IsActive
        {
            get;
            set;
        }
        public Nullable<bool> IsDelete
        {
            get;
            set;
        }
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            //btnAdmin_Click(btnAdmin, new EventArgs());

            var appsurl = ConfigurationManager.AppSettings["APIPath"].ToString();
            client.BaseAddress = new Uri(appsurl);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //HttpResponseMessage LoginUseR = client.GetAsync("MasterLoginUser").Result;
            //LoginList1 = LoginUseR.Content.ReadAsAsync<List<Master_Login_User>>().Result;
            var appsurl1 = ConfigurationManager.AppSettings["APIPath1"].ToString();
            client1.BaseAddress = new Uri(appsurl1);
            client1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));



            if (!IsPostBack)
            {
                #region....QueryString For Dolna User Type....

                string v = Request.QueryString["uid"];
                if (v != null)
                {
                    Session["ClientUser"] = v;
                }


                #endregion
                if (Request.IsAuthenticated)
                {

                    fill();
                    if (Session["Client"] == "Client")
                    {
                        string ecomercecloudloginid = "";
                        if (Session["ClientUser"] != null)
                        {
                            if (Session["ClientUser"].ToString() == "Gallerist")
                            {
                                HttpResponseMessage LoginUseR = client.GetAsync("MasterLoginUser").Result;
                                LoginList1 = LoginUseR.Content.ReadAsAsync<List<Master_Login_User>>().Result;
                                var dataG = (from a in LoginList1
                                             where a.Login_EmailId == Session["Email"].ToString() && a.IsERPClient_Member == true
                                             select new
                                             {
                                                 a.Login_User_ID,
                                                 a.IsERPClient_Member
                                             }).ToList();

                                if (dataG.Count() > 0)
                                {
                                    ecomercecloudloginid = dataG.ToList()[0].Login_User_ID.ToString();
                                    Response.Redirect("http://kencommerce.azurewebsites.net/Supplier/Default.aspx?CluoudLoginid=" + ecomercecloudloginid);
                                }

                            }
                            if (Session["ClientUser"].ToString() == "Artist")
                            {
                                HttpResponseMessage LoginUseR = client.GetAsync("MasterLoginUser").Result;
                                LoginList1 = LoginUseR.Content.ReadAsAsync<List<Master_Login_User>>().Result;

                                var dataL = (from a in LoginList1
                                             where a.Login_EmailId == Session["Email"].ToString() && a.IsERPClient_Member == true
                                             select new
                                             {
                                                 a.Login_User_ID,
                                                 a.IsERPClient_Member
                                             }).ToList();
                                if (dataL.Count() > 0)
                                {
                                    ecomercecloudloginid = dataL.ToList()[0].Login_User_ID.ToString();
                                    Response.Redirect("http://kencommerce.azurewebsites.net/Supplier/Default.aspx?CluoudLoginid=" + ecomercecloudloginid);
                                }
                                else
                                {
                                    Response.Redirect("~/unauthorizedPage.aspx", false);
                                }


                            }
                            if (Session["ClientUser"].ToString() == "Admin")
                            {
                                HttpResponseMessage LoginUseR = client.GetAsync("MasterLoginUser").Result;
                                LoginList1 = LoginUseR.Content.ReadAsAsync<List<Master_Login_User>>().Result;

                                var data = (from a in LoginList1
                                            where a.Login_EmailId == Session["Email"].ToString() && a.IsERPClient_Member == true
                                            select new
                                            {
                                                a.Login_User_ID,
                                                a.IsERPClient_Member
                                            }).ToList();

                                if (data.Count() > 0)
                                {
                                    ecomercecloudloginid = data.ToList()[0].Login_User_ID.ToString();
                                    Response.Redirect("~/Clients/ClientFirstLandingPage.aspx?CluoudLoginid=" + ecomercecloudloginid);
                                }
                                else
                                {
                                    Response.Redirect("~/unauthorizedPage.aspx", false);

                                }

                            }
                        }
                        else
                        {
                            HttpResponseMessage LoginUseR = client.GetAsync("MasterLoginUser").Result;
                            LoginList1 = LoginUseR.Content.ReadAsAsync<List<Master_Login_User>>().Result;

                            var data = (from a in LoginList1
                                        where a.Login_EmailId == Session["Email"].ToString() && a.IsERPClient_Member == true
                                        select new
                                        {
                                            a.Login_User_ID,
                                            a.IsERPClient_Member
                                        }).ToList();

                            if (data.Count() > 0)
                            {
                                Session["LoginId"] = data.ToList()[0].Login_User_ID;
                                Response.Redirect("~/Clients/ClientFirstLandingPage.aspx", false);
                            }
                            else
                            {
                                Response.Redirect("~/unauthorizedPage.aspx", false);

                            }
                        }

                    }
                    else if (Session["Client"] == "Admin")
                    {
                        HttpResponseMessage LoginUseR = client.GetAsync("MasterLoginUser").Result;
                        LoginList1 = LoginUseR.Content.ReadAsAsync<List<Master_Login_User>>().Result;

                        var data = (from a in LoginList1
                                    where a.Login_EmailId == Session["Email"].ToString() && a.IsSwash_AdminMember == true
                                    select new
                                    {
                                        a.Login_User_ID
                                    }).ToList();
                        if (data.Count() > 0)
                        {
                            Response.Redirect("~/SwashAdmin/SwashAdminLandingPage.aspx", false);
                        }
                        else
                        {
                            Response.Redirect("~/unauthorizedPage.aspx", false);

                        }



                    }
                    else if (Session["Client"] == "Partner")
                    {
                        HttpResponseMessage LoginUseR = client.GetAsync("MasterLoginUser").Result;
                        LoginList1 = LoginUseR.Content.ReadAsAsync<List<Master_Login_User>>().Result;

                        var data = (from a in LoginList1
                                    where a.Login_EmailId == Session["Email"].ToString() && a.IsPartner == true
                                    select new
                                    {
                                        a.Login_User_ID
                                    }).ToList();
                        if (data.Count() > 0)
                        {
                            Response.Redirect("~/Partner/PartnerLandingPage.aspx", false);

                        }
                        else
                        {
                            Response.Redirect("~/unauthorizedPage.aspx", false);

                        }

                    }
                    else
                    {





                    }

                }
            }

        }
        catch (Exception ex)
        {
            ex.Message.ToString();
        }
    }


    #region Azure B2c Claim Value

    [Authorize]
    public void fill()
    {
        // Get the claims values

        //Thread.Sleep(2000);
        //Claim displayName = ClaimsPrincipal.Current.FindFirst(ClaimsPrincipal.Current.Identities.First().NameClaimType);


        var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;

        // Get the claims values
        var exp1 = identity.Claims.Where(c => c.Type == "exp")
                           .Select(c => c.Value).SingleOrDefault();
        var nbf1 = identity.Claims.Where(c => c.Type == "nbf")
                           .Select(c => c.Value).SingleOrDefault();
        var ver1 = identity.Claims.Where(c => c.Type == "ver")
                           .Select(c => c.Value).SingleOrDefault();
        var nameidentifier1 = identity.Claims.Where(c => c.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier")
                           .Select(c => c.Value).SingleOrDefault();
        var aud1 = identity.Claims.Where(c => c.Type == "aud")
                           .Select(c => c.Value).SingleOrDefault();
        var authnclassreference1 = identity.Claims.Where(c => c.Type == "http://schemas.microsoft.com/claims/authnclassreference")
                           .Select(c => c.Value).SingleOrDefault();
        var nonce1 = identity.Claims.Where(c => c.Type == "nonce")
                           .Select(c => c.Value).SingleOrDefault();
        var iat1 = identity.Claims.Where(c => c.Type == "iat")
                           .Select(c => c.Value).SingleOrDefault();
        var authenticationinstant1 = identity.Claims.Where(c => c.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationinstant")
                           .Select(c => c.Value).SingleOrDefault();
        var name1 = identity.Claims.Where(c => c.Type == "name")
                           .Select(c => c.Value).SingleOrDefault();
        var identityprovider1 = identity.Claims.Where(c => c.Type == "http://schemas.microsoft.com/identity/claims/identityprovider")
                           .Select(c => c.Value).SingleOrDefault();
        var objectidentifier1 = identity.Claims.Where(c => c.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier")
                           .Select(c => c.Value).SingleOrDefault();
        var Email1 = identity.Claims.Where(c => c.Type == "emails")
                           .Select(c => c.Value).SingleOrDefault();
        var country = identity.Claims.Where(c => c.Type == "country")
                         .Select(c => c.Value).SingleOrDefault();
        var state1 = identity.Claims.Where(c => c.Type == "state")
                           .Select(c => c.Value).SingleOrDefault();
        var postalCode1 = identity.Claims.Where(c => c.Type == "postalCode")
                           .Select(c => c.Value).SingleOrDefault();
        var city1 = identity.Claims.Where(c => c.Type == "city")
                           .Select(c => c.Value).SingleOrDefault();
        var extension_Mobile1 = identity.Claims.Where(c => c.Type == "extension_Mobile")
                           .Select(c => c.Value).SingleOrDefault();
        var issuer = identity.Claims.Where(c => c.Type == "iss")
                           .Select(c => c.Value).SingleOrDefault();
        // Cast the Thread.CurrentPrincipal
        ClaimsPrincipal icp = Thread.CurrentPrincipal as ClaimsPrincipal;

        // Access IClaimsIdentity which contains claims
        ClaimsIdentity claimsIdentity = (ClaimsIdentity)icp.Identity;
        string exp = exp1;
        string nbf = nbf1;
        string ver = ver1;
        string nameidentifier = nameidentifier1;
        string aud = aud1;
        string authnclassreference = authnclassreference1;
        string nonce = nonce1;
        string iat = iat1;
        string authenticationinstant = authenticationinstant1;
        string name = name1;
        string identityprovider = identityprovider1;
        string objectidentifier = objectidentifier1;
        string Email = Email1;
        string state = state1;
        string postalCode = postalCode1;
        string city = city1;
        string extension_Mobile = extension_Mobile1;
        string Country = country;
        ViewState["ObjectId"] = objectidentifier;


        var ctx = HttpContext.Current.GetOwinContext();
        ClaimsPrincipal user = ctx.Authentication.User;
        IEnumerable<Claim> claims = user.Claims;
        var ClaimList = ClaimsPrincipal.Current.Claims.ToList();
        if (ClaimList.Count() > 0)
        {
            Session["objectidentifier"] = objectidentifier;
            Session["Email"] = Email;

            HttpResponseMessage hrm = client.GetAsync("MasterLoginUser").Result;


            if (hrm.IsSuccessStatusCode)
            {
                LoginList1 = hrm.Content.ReadAsAsync<List<Master_Login_User>>().Result;
                var data = from c in LoginList1
                           select c;
                var check = from c in data.Where(t => t.Azure_ObjectID == objectidentifier)
                            select c;
                if (Convert.ToInt32(check.Count()) > 0)
                {
                    string FullName = check.ToList().First().Login_Username;
                    Session["DisplayName"] = FullName;
                    string getRegdid = check.ToList().First().User_RegistrationId.ToString();
                    string getloginid = check.ToList().First().Login_User_ID.ToString();
                    Session["Login_User_Id"] = getloginid;
                    Session["RegistrationId"] = getRegdid;

                    ///////////Insert While Login//////////////////
                    #region Insert While Login

                    HttpResponseMessage desi = client.GetAsync("MasterLoginHistory").Result;
                    if (desi.IsSuccessStatusCode)
                    {
                        loginhistory = desi.Content.ReadAsAsync<List<Master_Login_History>>().Result;
                        var checkloginhistory = from c in loginhistory.Where(t => t.User_LogOutTime == null && t.Login_User_ID == Convert.ToInt32(getloginid))
                                                select c;
                        if (Convert.ToInt32(checkloginhistory.Count()) > 0)
                        {


                        }
                        else
                        {
                            Master_Azure_StaticReturnValue tp = new Master_Azure_StaticReturnValue();
                            tp.Azure_ObjectID = objectidentifier;
                            tp.Azure_ClassReference = authnclassreference;
                            tp.Azure_Issuer = issuer;
                            tp.Azure_ApplicationId = aud;
                            tp.Azure_Version = ver;
                            tp.InsertedOn = DateTime.Now;
                            tp.InsertedBy = Convert.ToInt32(getRegdid);
                            tp.IsActive = true;
                            tp.IsDelete = false;
                            var response = client.PostAsJsonAsync("MasterAzureStaticReturnValue", tp).Result;
                            if (response.IsSuccessStatusCode)
                            {
                                string StaticId = response.Content.ReadAsStringAsync().Result;
                                // Session["Azure_objectSerial_Id"] = StaticId;



                                //======Master_Azure_DynamicReturnValue
                                Master_Azure_DynamicReturnValue AzDy = new Master_Azure_DynamicReturnValue();
                                AzDy.Azure_authenticationInstant = authenticationinstant;
                                AzDy.Azure_exp = exp;
                                AzDy.Azure_IssuedAt = iat;
                                AzDy.Azure_NameIdentifier = nameidentifier;
                                AzDy.Azure_nbf = nbf;
                                AzDy.InsertedOn = DateTime.Now;
                                AzDy.InsertedBy = Convert.ToInt32(getRegdid);
                                AzDy.IsActive = true;
                                AzDy.IsDelete = false;
                                AzDy.Azure_Nonce = nonce;
                                AzDy.Azure_ObjectSerial_Id = Convert.ToInt32(StaticId);
                                AzDy.User_RegistrationId = Convert.ToInt32(getRegdid);
                                var response1 = client.PostAsJsonAsync("MasterAzureDynamicReturnValue", AzDy).Result;
                                if (response1.IsSuccessStatusCode)
                                {
                                    //========= Master_Device_Type
                                    HttpBrowserCapabilities objBrwInfo = Request.Browser;
                                    string hostName = Dns.GetHostName(); // Retrive the Name of HOST

                                    Master_Device_Type DvTyp = new Master_Device_Type();
                                    DvTyp.Device_Name = Dns.GetHostName();
                                    DvTyp.Device_Model = "Desktop";
                                    DvTyp.InsertedOn = DateTime.Now;
                                    DvTyp.InsertedBy = Convert.ToInt32(getRegdid);
                                    DvTyp.IsActive = true;
                                    DvTyp.IsDelete = false;
                                    // mdt.Device_Name = Request.UserHostName;
                                    DvTyp.Device_Type = objBrwInfo.Type;
                                    DvTyp.Device_OS_Type = getOperatinSystemDetails(Request.UserAgent);
                                    DvTyp.Device_OS_Version = getOperatinSystemDetails(Request.UserAgent);
                                    DvTyp.Device_MacAddress = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString();
                                    var response2 = client.PostAsJsonAsync("MasterDeviceType", DvTyp).Result;
                                    if (response2.IsSuccessStatusCode)
                                    {
                                        string Device_ID = response2.Content.ReadAsStringAsync().Result;
                                        //Session["Azure_objectSerial_Id"] = Device_ID;


                                        //=========================Master_Device_Registration
                                        Master_Device_Registration DevReg = new Master_Device_Registration();
                                        DevReg.User_RegistrationId = Convert.ToInt32(getRegdid);
                                        if (GetDefaultGateway() != null)
                                        {
                                            DevReg.Device_PublicIPGateway = GetDefaultGateway().ToString();
                                        }
                                        DevReg.Device_LocalIPAddress = Dns.GetHostByName(hostName).AddressList[0].ToString();
                                        DevReg.Device_ID = Convert.ToInt32(Device_ID);
                                        DevReg.InsertedOn = DateTime.Now;
                                        DevReg.InsertedBy = Convert.ToInt32(getRegdid);
                                        DevReg.IsActive = true;
                                        DevReg.IsDelete = false;
                                        var response3 = client.PostAsJsonAsync("MasterDeviceRegistration", DevReg).Result;
                                        if (response3.IsSuccessStatusCode)
                                        {

                                            string Device_RegistrationId = response3.Content.ReadAsStringAsync().Result;


                                            //============
                                            if (Device_RegistrationId != null)
                                            {
                                                Master_Login_History LognHsty = new Master_Login_History();
                                                LognHsty.Login_User_ID = Convert.ToInt32(getloginid);
                                                LognHsty.Device_RegistrationId = Convert.ToInt32(Device_RegistrationId);
                                                LognHsty.InsertedOn = DateTime.Now;
                                                LognHsty.InsertedBy = Convert.ToInt32(getRegdid);
                                                LognHsty.IsActive = true;
                                                LognHsty.IsDelete = false;

                                                TimeSpan CurrentTime = DateTime.Now.TimeOfDay;
                                                LognHsty.User_LoginTime = CurrentTime; //TimeSpan(DateTime.Now.ToShortTimeString());//DateTime.Now.ToString("hh:mm:ss.fff tt", System.Globalization.DateTimeFormatInfo.InvariantInfo;
                                                LognHsty.User_LogInDate = DateTime.Now;
                                                var response4 = client.PostAsJsonAsync("MasterLoginHistory", LognHsty).Result;
                                                if (response4.IsSuccessStatusCode)
                                                {

                                                    Master_Device_Registration mdrg = new Master_Device_Registration();
                                                    mdrg.Device_RegistrationId = Convert.ToInt32(Device_RegistrationId);
                                                    mdrg.Is_Referred = true;
                                                    var response5 = client.PutAsJsonAsync("MasterDeviceRegistration", mdrg).Result;

                                                }

                                            }
                                            else
                                            {
                                                Master_Login_History LognHsty = new Master_Login_History();
                                                //  mlh.Login_User_ID = Convert.ToInt32(logid.ToList().Last());
                                                //  mlh.Device_RegistrationId = Convert.ToInt32(deviceregd.ToList().Last());
                                                LognHsty.InsertedOn = DateTime.Now;
                                                LognHsty.InsertedBy = Convert.ToInt32(getRegdid);
                                                LognHsty.IsActive = true;
                                                LognHsty.IsDelete = false;

                                                TimeSpan CurrentTime = DateTime.Now.TimeOfDay;
                                                LognHsty.User_LoginTime = CurrentTime; //TimeSpan(DateTime.Now.ToShortTimeString());//DateTime.Now.ToString("hh:mm:ss.fff tt", System.Globalization.DateTimeFormatInfo.InvariantInfo;
                                                LognHsty.User_LogInDate = DateTime.Now;
                                                var response4 = client.PostAsJsonAsync("MasterLoginHistory", LognHsty).Result;

                                            }
                                            //============
                                        }
                                        else
                                        {

                                        }
                                        //=========
                                    }
                                    else
                                    {

                                    }
                                    // ====
                                }
                                else
                                {

                                }
                                //===========
                            }
                            else
                            {

                            }
                        }
                    }
                    else
                    {

                    }


                    #endregion
                    /////////////End  Insert While Login//////////////////
                }
                else
                {
                    /////////////  Insert While SignUp//////////////////
                    #region Insert While Signup
                    HttpResponseMessage desi = client.GetAsync("MasterLoginHistory").Result;

                    if (desi.IsSuccessStatusCode)
                    {
                        //string FullName = check.ToList().First().Login_Username.ToString() != null ? check.ToList().First().Login_Username.ToString() : string.Empty;
                        HttpBrowserCapabilities objBrwInfo = Request.Browser;
                        string Name = name;
                        string[] nmArr12 = name.Split(' ');
                        ViewState["name"] = nmArr12[0].ToString();
                        string FirstName = "", MiddleName = "", LastName = "", Title = "";
                        if (Name != null)
                        {
                            string[] nmArr = Name.Split(' ');
                            if (nmArr.Count() == 4)
                            {
                                FirstName = nmArr[0].ToString() + " " + nmArr[1].ToString();
                                MiddleName = nmArr[2].ToString();
                                LastName = nmArr[3].ToString();
                            }
                            else if (nmArr.Count() == 3)
                            {
                                FirstName = nmArr[0].ToString();
                                MiddleName = nmArr[1].ToString();
                                LastName = nmArr[2].ToString();
                            }
                            else if (nmArr.Count() == 2)
                            {
                                FirstName = nmArr[0].ToString();
                                LastName = nmArr[1].ToString();
                            }
                            else if (nmArr.Count() == 1)
                            {
                                FirstName = nmArr[0].ToString();
                            }
                        }

                        Session["DisplayName"] = FirstName + " " + MiddleName + " " + LastName;
                        ////////////////////////////For Create a blob Container and getting path//////////////////

                        ////////////////////////////For Create a blob Container//////////////////

                        //**Master User Registration**//
                        Master_User_Registration tr = new Master_User_Registration();
                        //tr.ClientId = "SWASH";
                        tr.User_Title = "";
                        tr.User_First_Name = FirstName.ToString();
                        tr.User_Middle_Name = MiddleName.ToString();
                        tr.User_Last_Name = LastName.ToString();
                        tr.User_MobileNo = extension_Mobile;
                        tr.User_CountryName = Country;
                        tr.User_StateName = state;
                        tr.User_CityName = city;
                        tr.User_ZipCode = postalCode;
                        tr.User_EmailId = Email;
                        tr.Is_Referred = true;
                        tr.InsertedOn = DateTime.Now;
                        tr.IsActive = true;
                        tr.IsDelete = false;
                        //tr.User_RegistrationId = Master_User_RegistrationEntity.User_RegistrationId,
                        //tr.User_BlobContainer_Path = ViewState["BlobPath"].ToString();

                        var res = client.PostAsJsonAsync("MasterUserRegistration", tr).Result;

                        if (res.IsSuccessStatusCode)
                        {
                            string RegistrationId = res.Content.ReadAsStringAsync().Result;
                            //string s = cv.Replace(@"\", string.Empty);
                            //string final = s.Trim().Substring(1, (s.Length) - 2);

                            Session["RegistrationId"] = RegistrationId;
                            createCointainer();

                            ////****Master Azure StaticReturnValue****//
                            Master_Azure_StaticReturnValue tp = new Master_Azure_StaticReturnValue();
                            tp.Azure_ObjectID = objectidentifier;
                            tp.Azure_Version = ver;
                            tp.Azure_Issuer = issuer;
                            tp.Azure_ApplicationId = aud;
                            tp.Azure_ClassReference = HttpContext.Current.Request["Azure_ClassReference"];
                            tp.InsertedBy = Convert.ToInt32(Session["RegistrationId"]);
                            tp.InsertedOn = DateTime.Now;
                            tp.IsActive = true;
                            tp.IsDelete = false;

                            var azuS = client.PostAsJsonAsync("MasterAzureStaticReturnValue", tp).Result;
                            if (azuS.IsSuccessStatusCode)
                            {
                                string StaticId = azuS.Content.ReadAsStringAsync().Result;
                                Session["Azure_objectSerial_Id"] = StaticId;

                                //    //****Master Azure DynamicReturnValue****//
                                Master_Azure_DynamicReturnValue AzDy = new Master_Azure_DynamicReturnValue();
                                AzDy.Azure_nbf = nbf1;
                                AzDy.Azure_exp = exp1;
                                AzDy.Azure_NameIdentifier = nameidentifier;
                                AzDy.Azure_Nonce = nonce;
                                AzDy.Azure_IssuedAt = iat;
                                AzDy.Azure_authenticationInstant = authenticationinstant;
                                AzDy.Return_Type = "";
                                AzDy.Return_Value = "";
                                AzDy.User_RegistrationId = Convert.ToInt32(Session["RegistrationId"]);
                                AzDy.Azure_ObjectSerial_Id = Convert.ToInt32(Session["Azure_objectSerial_Id"]);
                                AzDy.InsertedBy = Convert.ToInt32(Session["RegistrationId"]);
                                AzDy.InsertedOn = System.DateTime.Now;
                                AzDy.IsActive = true;
                                AzDy.IsDelete = false;

                                var azuD = client.PostAsJsonAsync("MasterAzureDynamicReturnValue", AzDy).Result;

                                if (azuD.IsSuccessStatusCode)
                                {
                                    string DynamicId = azuD.Content.ReadAsStringAsync().Result;

                                    //****Master Login User****//
                                    Master_Login_User lg = new Master_Login_User();
                                    lg.User_RegistrationId = Convert.ToInt32(Session["RegistrationId"]);
                                    lg.Azure_ObjectID = objectidentifier;
                                    lg.Login_EmailId = Email1;
                                    lg.Login_Username = Session["DisplayName"].ToString();
                                    lg.Login_Password = null;
                                    lg.Login_Pin = null;
                                    lg.Login_SecretQuestion = null;
                                    lg.Login_SecretAnswer = null;
                                    lg.Login_Registered_MobileNumber = null;


                                    if (Session["Client"] == "Client")
                                    {
                                        lg.Partner_ID = null;
                                        lg.IsPartner = false;
                                        lg.IsERPClient_Member = true;
                                        lg.IsSwash_AdminMember = false;
                                        lg.IsActive = true;
                                        lg.IsDelete = false;
                                        lg.InsertedOn = System.DateTime.Now;
                                        lg.Is_Referred = true;
                                    }
                                    else if (Session["Client"] == "Admin")
                                    {
                                        lg.Partner_ID = null;
                                        lg.IsPartner = false;
                                        lg.IsERPClient_Member = false;
                                        lg.IsSwash_AdminMember = true;
                                        lg.IsActive = true;
                                        lg.IsDelete = false;
                                        lg.InsertedOn = System.DateTime.Now;
                                        lg.Is_Referred = true;

                                    }
                                    else
                                    {
                                        lg.Partner_ID = null;
                                        lg.IsPartner = true;
                                        lg.IsERPClient_Member = false;
                                        lg.IsSwash_AdminMember = false;
                                        lg.IsActive = true;
                                        lg.IsDelete = false;
                                        lg.InsertedOn = System.DateTime.Now;
                                        lg.Is_Referred = true;

                                    }

                                    var LoginUser = client.PostAsJsonAsync("MasterLoginUser", lg).Result;
                                    if (LoginUser.IsSuccessStatusCode)
                                    {
                                        string LoginUserId = LoginUser.Content.ReadAsStringAsync().Result;
                                        Session["Login_User_Id"] = LoginUserId;



                                        //****Master Admin Login Lookup****//
                                        Master_Admin_Login_Lookup logLk = new Master_Admin_Login_Lookup();
                                        logLk.Login_User_ID = Convert.ToInt32(Session["Login_User_Id"]);
                                        logLk.Client_ID = null;
                                        if (Session["Client"] == "Client")
                                        {
                                            if (Session["ClientUser"] != null)
                                            {
                                                if (Session["ClientUser"].ToString() == "Artist")
                                                {
                                                    logLk.Is_Super_Admin = false;
                                                    logLk.Is_User_Admin = true;
                                                    logLk.Is_Configurator = false;
                                                    logLk.Is_Swash_Admin = false;
                                                    logLk.Is_Swash_User = false;
                                                }
                                                if (Session["ClientUser"].ToString() == "Gallerist")
                                                {
                                                    logLk.Is_Super_Admin = false;
                                                    logLk.Is_User_Admin = true;
                                                    logLk.Is_Configurator = false;
                                                    logLk.Is_Swash_Admin = false;
                                                    logLk.Is_Swash_User = false;
                                                }
                                                if (Session["ClientUser"].ToString() == "Admin")
                                                {
                                                    logLk.Is_Super_Admin = false;
                                                    logLk.Is_User_Admin = true;
                                                    logLk.Is_Configurator = false;
                                                    logLk.Is_Swash_Admin = false;
                                                    logLk.Is_Swash_User = false;
                                                }

                                            }
                                            else
                                            {
                                                logLk.Is_Super_Admin = true;
                                                logLk.Is_User_Admin = false;
                                                logLk.Is_Configurator = false;
                                                logLk.Is_Swash_Admin = false;
                                                logLk.Is_Swash_User = false;
                                            }

                                        }
                                        else if (Session["Client"] == "Admin")
                                        {
                                            logLk.Is_Super_Admin = false;
                                            logLk.Is_User_Admin = false;
                                            logLk.Is_Configurator = false;
                                            logLk.Is_Swash_Admin = false;
                                            logLk.Is_Swash_User = false;

                                        }
                                        else
                                        {
                                            logLk.Is_Super_Admin = false;
                                            logLk.Is_User_Admin = false;
                                            logLk.Is_Configurator = false;
                                            logLk.Is_Swash_Admin = false;
                                            logLk.Is_Swash_User = false;

                                        }


                                        logLk.Is_Approver = null;
                                        logLk.InsertedBy = Convert.ToInt32(Session["RegistrationId"]);
                                        logLk.InsertedOn = System.DateTime.Now;
                                        logLk.IsActive = true;
                                        logLk.IsDelete = false;

                                        var LoglookUp = client.PostAsJsonAsync("MasterAdminLoginLookup", logLk).Result;
                                        if (LoglookUp.IsSuccessStatusCode)
                                        {

                                            //****Master Login Version****//
                                            Master_Login_Version lgvs = new Master_Login_Version();
                                            lgvs.Login_User_ID = Convert.ToInt32(Session["Login_User_Id"]);
                                            lgvs.Login_Change_Version = null;
                                            lgvs.Login_Type_Version = null;
                                            lgvs.Login_Change_Description = null;
                                            lgvs.Login_Parameter_OldValue = null;
                                            lgvs.Login_Parameter_NewValue = null;
                                            lgvs.ConfirmationCode = null;
                                            lgvs.Confirmation_Code_ID = null;
                                            lgvs.InsertedBy = Convert.ToInt32(Session["RegistrationId"]);
                                            lgvs.InsertedOn = System.DateTime.Now;

                                            var LoginVersion = client.PostAsJsonAsync("MasterLoginVersion", lgvs).Result;
                                            if (LoginVersion.IsSuccessStatusCode)
                                            {

                                                //**Master Device Type**//
                                                string hostName = Dns.GetHostName();
                                                Master_Device_Type DvTyp = new Master_Device_Type();
                                                DvTyp.Device_Name = Dns.GetHostName();
                                                DvTyp.Device_Type = objBrwInfo.Type;
                                                DvTyp.Device_Model = "Desktop";
                                                DvTyp.Device_OS_Type = getOperatinSystemDetails(Request.UserAgent);
                                                DvTyp.Device_OS_Version = getOperatinSystemDetails(Request.UserAgent);
                                                DvTyp.Device_Manufacture = null;
                                                DvTyp.Device_MacAddress = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString();
                                                DvTyp.InsertedOn = System.DateTime.Now;
                                                DvTyp.InsertedBy = Convert.ToInt32(Session["RegistrationId"]);
                                                DvTyp.IsActive = true;
                                                DvTyp.IsDelete = false;

                                                var DeviceType = client.PostAsJsonAsync("MasterDeviceType", DvTyp).Result;
                                                if (DeviceType.IsSuccessStatusCode)
                                                {
                                                    string DeviceTypeId = DeviceType.Content.ReadAsStringAsync().Result;


                                                    Session["Device_ID"] = DeviceTypeId;

                                                    //                        //**Master Device Registration**//
                                                    Master_Device_Registration DevReg = new Master_Device_Registration();
                                                    DevReg.User_RegistrationId = Convert.ToInt32(Session["RegistrationId"]);
                                                    DevReg.Device_ID = Convert.ToInt32(Session["Device_ID"]);
                                                    DevReg.Client_ID = null;
                                                    DevReg.Device_UI_Type = null;
                                                    DevReg.Device_UI_RegistrationID = null;
                                                    DevReg.Device_LocalIPAddress = Dns.GetHostByName(hostName).AddressList[0].ToString();
                                                    //  DevReg.Device_PublicIPGateway = GetDefaultGateway().ToString();
                                                    DevReg.InsertedOn = System.DateTime.Now;
                                                    DevReg.IsActive = true;
                                                    DevReg.IsDelete = false;

                                                    var DeviceRegistration = client.PostAsJsonAsync("MasterDeviceRegistration", DevReg).Result;
                                                    if (DeviceRegistration.IsSuccessStatusCode)
                                                    {
                                                        string DeviceRegistrationId = DeviceRegistration.Content.ReadAsStringAsync().Result;

                                                        Session["Device_RegistrationId"] = DeviceRegistrationId;

                                                        //                            //**Master Login History**//
                                                        Master_Login_History LognHsty = new Master_Login_History();
                                                        LognHsty.Login_User_ID = Convert.ToInt32(Session["Login_User_Id"]);
                                                        LognHsty.Device_RegistrationId = Convert.ToInt32(Session["Device_RegistrationId"]);
                                                        LognHsty.User_LogInDate = DateTime.Now;
                                                        LognHsty.User_LogOutDate = null;
                                                        TimeSpan CurrentTime = DateTime.Now.TimeOfDay;
                                                        LognHsty.User_LoginTime = CurrentTime;
                                                        LognHsty.User_LogOutTime = null;
                                                        LognHsty.Login_False_Hit_Attempt = null;
                                                        LognHsty.InsertedBy = Convert.ToInt32(Session["RegistrationId"]);
                                                        LognHsty.InsertedOn = System.DateTime.Now;
                                                        LognHsty.IsActive = true;
                                                        LognHsty.IsDelete = false;

                                                        var LoginHistory = client.PostAsJsonAsync("MasterLoginHistory", LognHsty).Result;
                                                        if (LoginHistory.IsSuccessStatusCode)
                                                        {
                                                            if (Session["Client"] == "Client")
                                                            {
                                                                ///**Master_ERPClient member**////
                                                                Master_ERPClient_Member erpMember = new Master_ERPClient_Member();
                                                                erpMember.Login_User_ID = Convert.ToInt32(Session["Login_User_Id"]);
                                                                erpMember.InsertedBy = Convert.ToInt32(Session["RegistrationId"]);
                                                                erpMember.InsertedOn = System.DateTime.Now;
                                                                erpMember.IsActive = true;
                                                                erpMember.IsDelete = false;
                                                                var ERPClient = client.PostAsJsonAsync("MasterERPClientMember", erpMember).Result;
                                                                if (ERPClient.IsSuccessStatusCode)
                                                                {
                                                                    /////**Master_ClientRegstn**////
                                                                    Client_Registration adminLkUp = new Client_Registration();
                                                                    adminLkUp.User_RegistrationId = Convert.ToInt32(Session["RegistrationId"]);
                                                                    adminLkUp.Client_Application_UniqueViewID = getGenerated();
                                                                    //adminLkUp.Is_Swash_Admin = false;
                                                                    //adminLkUp.Is_Swash_User = false;
                                                                    //adminLkUp.Is_User_Admin = false;
                                                                    //adminLkUp.Is_Configurator = false;
                                                                    //adminLkUp.Is_Approver = false;
                                                                    adminLkUp.InsertedOn = System.DateTime.Now;
                                                                    adminLkUp.InsertedBy = Convert.ToInt32(Session["RegistrationId"]);
                                                                    adminLkUp.IsActive = true;
                                                                    adminLkUp.IsDelete = false;
                                                                    var ADMINlogin = client.PostAsJsonAsync("ClientRegistration", adminLkUp).Result;
                                                                    if (ADMINlogin.IsSuccessStatusCode)
                                                                    {

                                                                    }
                                                                }
                                                            }
                                                            else if (Session["Client"] == "Admin")
                                                            {
                                                                ///**Master_Admin_Login_Lookup**////
                                                                Master_Admin_Login_Lookup adminLkUp = new Master_Admin_Login_Lookup();
                                                                adminLkUp.Login_User_ID = Convert.ToInt32(Session["Login_User_Id"]);
                                                                adminLkUp.Is_Super_Admin = false;
                                                                adminLkUp.Is_Swash_Admin = true;
                                                                adminLkUp.Is_Swash_User = false;
                                                                adminLkUp.Is_User_Admin = false;
                                                                adminLkUp.Is_Configurator = false;
                                                                adminLkUp.Is_Approver = false;
                                                                adminLkUp.InsertedOn = System.DateTime.Now;
                                                                adminLkUp.InsertedBy = Convert.ToInt32(Session["RegistrationId"]);
                                                                adminLkUp.IsActive = true;
                                                                adminLkUp.IsDelete = false;
                                                                var ADMINlogin = client.PostAsJsonAsync("MasterAdminLoginLookup", adminLkUp).Result;
                                                                if (ADMINlogin.IsSuccessStatusCode)
                                                                {

                                                                }

                                                            }
                                                            else
                                                            {
                                                                ///**Master_kenPartner**///
                                                                Master_KenPartner kenprt = new Master_KenPartner();
                                                                kenprt.Login_User_ID = Convert.ToInt32(Session["Login_User_Id"]);
                                                                kenprt.InsertedOn = System.DateTime.Now;
                                                                kenprt.InsertedBy = Convert.ToInt32(Session["RegistrationId"]);
                                                                kenprt.IsActive = true;
                                                                kenprt.IsDelete = false;
                                                                var KenPartnr = client.PostAsJsonAsync("MasterKenPartner", kenprt).Result;
                                                                if (KenPartnr.IsSuccessStatusCode)
                                                                {
                                                                    ///**KP Application**///
                                                                    KP_Application kpAppn = new KP_Application();
                                                                    kpAppn.User_RegistrationId = Convert.ToInt32(Session["RegistrationId"]);
                                                                    kpAppn.Apllication_UniqueViewID = Generate();
                                                                    kpAppn.IsActive = true;
                                                                    kpAppn.IsDelete = false;
                                                                    kpAppn.InsertedBy = Convert.ToInt32(Session["RegistrationId"]);
                                                                    kpAppn.InsertedOn = System.DateTime.Now;
                                                                    var KPapplication = client.PostAsJsonAsync("KPApplication", kpAppn).Result;
                                                                    if (KPapplication.IsSuccessStatusCode)
                                                                    {
                                                                        string ApplicationID = KPapplication.Content.ReadAsStringAsync().Result;
                                                                        Session["ApplicationId"] = ApplicationID;
                                                                    }

                                                                }


                                                            }


                                                        }
                                                        else
                                                        {

                                                        }


                                                    }
                                                    else
                                                    {

                                                    }


                                                }
                                                else
                                                {

                                                }


                                            }
                                            else
                                            {

                                            }

                                        }


                                    }
                                    else
                                    {

                                    }



                                }
                                else
                                {

                                }


                            }
                            else
                            {
                            }

                        }

                    }
                    else
                    {

                    }


                    #endregion

                    #region Kencommerce Login Database
                    if (Session["Client"].ToString() == "Client")
                    {
                        Master_Login_Users lg1 = new Master_Login_Users();
                        if (Session["Login_User_Id"] != null)
                        {
                            lg1.Cloud_Login_ID = Convert.ToInt32(Session["Login_User_Id"].ToString());
                        }
                        else
                        {
                            lg1.Cloud_Login_ID = null;
                        }
                        if (Session["ClientUser"].ToString() != null)
                        {
                            lg1.Login_User_Type = Session["ClientUser"].ToString();
                        }
                        lg1.Login_EmailId = Email1;
                        lg1.Login_MobileNo = extension_Mobile;
                        lg1.Login_Username = Session["DisplayName"].ToString();
                        lg1.Login_Password = null;
                        lg1.IsActive = true;
                        lg1.IsDelete = false;

                        HttpResponseMessage content = client1.PostAsJsonAsync("api/User", lg1).Result;
                    }
                    #endregion

                }
            }

        }


    }

    private string getGenerated()
    {
        HttpResponseMessage dt = client.GetAsync("ClientRegistration").Result;
        if (dt.IsSuccessStatusCode)
        {
            ClientRegistration = dt.Content.ReadAsAsync<List<Client_Registration>>().Result;
        }
        String preFix = "";
        preFix = "SCT-C01-";
        String ClientViewNo = "";
        var ClientViewID = ClientRegistration;
        if (ClientViewID.Count().Equals(0))
        {
            ClientViewNo = preFix + "000001";
        }
        else
        {
            var vd = (from c in ClientRegistration
                      select c.Client_Application_UniqueViewID);
            double LastClientViewNo = Convert.ToDouble(vd.ToList().Max().ToString().Substring(7));
            LastClientViewNo = LastClientViewNo + 1;
            ClientViewNo = preFix + LastClientViewNo.ToString("000000");
        }
        return ClientViewNo;
    }

    private string Generate()
    {
        {


            try
            {
                HttpResponseMessage dt = client.GetAsync("KPApplication").Result;
                if (dt.IsSuccessStatusCode)
                {
                    KPApplication = dt.Content.ReadAsAsync<List<KP_Application>>().Result;
                }
                String preFix = "";
                preFix = "AP-B01-";
                String ApplicationNo = "";
                var ApplicationNum = KPApplication;
                if (ApplicationNum.Count().Equals(0))
                {
                    ApplicationNo = preFix + "000001";
                }
                else
                {
                    var vd = (from c in KPApplication
                              select c.Apllication_UniqueViewID);
                    double LastApplicationNo = Convert.ToDouble(vd.ToList().Max().ToString().Substring(7));
                    LastApplicationNo = LastApplicationNo + 1;
                    ApplicationNo = preFix + LastApplicationNo.ToString("000000");
                }
                return ApplicationNo;
            }

            catch (Exception ex)
            {
                throw ex;
            }

        }
    }
    public string ByteArrayToString(byte[] input)
    {
        UTF8Encoding enc = new UTF8Encoding();
        string str = enc.GetString(input);
        return str;
    }
    public class getid
    {
        public int id
        {
            get;
            set;
        }
    }
    #endregion

    #region Azure B2c Methods
    public void SignIn()
    {
        if (!Request.IsAuthenticated)
        {
            // To execute a policy, you simply need to trigger an OWIN challenge.
            // You can indicate which policy to use by specifying the policy id as the AuthenticationType
            HttpContext.Current.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties()
                {
                    RedirectUri = "/"
                }, Startup.SignInPolicyId);
        }
    }
    public void SignUp()
    {
        if (!Request.IsAuthenticated)
        {
            HttpContext.Current.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties()
                {
                    RedirectUri = "/"
                }, Startup.SignUpPolicyId);
        }
    }
    public void ClientSignIn()
    {
        if (!Request.IsAuthenticated)
        {
            // To execute a policy, you simply need to trigger an OWIN challenge.
            // You can indicate which policy to use by specifying the policy id as the AuthenticationType
            HttpContext.Current.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties()
                {
                    RedirectUri = "/"
                }, Startup.ClientSignInPolicyId);
        }
    }
    public void ClientSignUp()
    {
        if (!Request.IsAuthenticated)
        {
            HttpContext.Current.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties()
                {
                    RedirectUri = "/"
                }, Startup.ClientSignUpPolicyId);
        }
    }
    public void ResetPassword()
    {
        if (!Request.IsAuthenticated)
        {
            HttpContext.Current.GetOwinContext().Authentication.Challenge(
            new AuthenticationProperties()
            {
                RedirectUri = "/"
            }, Startup.PasswordResetPolicyId);
        }
    }

    //public void Profile()
    //{
    //    if (Request.IsAuthenticated)
    //    {
    //        HttpContext.Current.GetOwinContext().Authentication.Challenge(
    //            new AuthenticationProperties() { RedirectUri = "/" }, Startup.ProfilePolicyId);
    //    }
    //}
    #endregion

    #region Create Blob Container
    public static CloudStorageAccount GetConnectionString()
    {
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
        return storageAccount;
    }
    public void createCointainer()
    {
        //string folder = ViewState["ObjectId"].ToString();
        //CloudStorageAccount cloudStorageAccount = GetConnectionString();
        //CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
        //CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(folder);
        //cloudBlobContainer.CreateIfNotExists();
        //string imageFullPath = cloudBlobContainer.Uri.ToString(); 




        string ss = ViewState["name"].ToString();

        string folder = ss.ToLower() + ViewState["ObjectId"].ToString();



        HttpResponseMessage desi = client.GetAsync("MasterUserRegistration").Result;
        if (desi.IsSuccessStatusCode)
        {
            MasterUserRegdList = desi.Content.ReadAsAsync<List<Master_User_Registration>>().Result;

            int userRegId = Convert.ToInt32(Session["RegistrationId"]);
            Master_User_Registration tr = MasterUserRegdList.Where(x => x.User_RegistrationId == userRegId).FirstOrDefault();
            tr.User_RegistrationId = Convert.ToInt32(Session["RegistrationId"]);
            tr.User_BlobContainer_Path = folder;
            HttpResponseMessage res = client.PutAsJsonAsync("MasterUserRegistration/" + userRegId, tr).Result;
            if (res.IsSuccessStatusCode)
            {

            }
        }

        CloudStorageAccount cloudStorageAccount = GetConnectionString();
        CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
        CloudBlobContainer container = cloudBlobClient.GetContainerReference(folder);
        container.CreateIfNotExists();
        // Retrieve reference to a blob named "myblob".  
        int count = 3;
        for (int i = 0; i <= count; i++)
        {
            string obj = Server.MapPath("~/Images/KENCloud-Logo.png");

            // string obj = "https://kenmaster.azurewebsites.net/Images/accent.png";
            var filename = Path.GetFileName(obj);
            if (i == 0)
            {
                CloudBlobDirectory Img = container.GetDirectoryReference(folder + "image");
                string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(filename);
                CloudBlockBlob cloudBlockBlob = Img.GetBlockBlobReference(imageName);
                CloudBlobClient blobClient1 = cloudStorageAccount.CreateCloudBlobClient();

                using (var fs = File.OpenRead(obj))
                {
                    cloudBlockBlob.UploadFromStream(fs);
                }

                string imageFullPath = container.Uri.ToString();
                ViewState["BlobPath"] = imageFullPath;

            }
            if (i == 1)
            {
                CloudBlobDirectory Img = container.GetDirectoryReference(folder + "video");
                string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(filename);
                CloudBlockBlob cloudBlockBlob = Img.GetBlockBlobReference(imageName);
                CloudBlobClient blobClient1 = cloudStorageAccount.CreateCloudBlobClient();
                using (var fs = File.OpenRead(obj))
                {
                    cloudBlockBlob.UploadFromStream(fs);
                }

                string imageFullPath = container.Uri.ToString();
                ViewState["BlobPath"] = imageFullPath;

            }
            if (i == 2)
            {
                CloudBlobDirectory Img = container.GetDirectoryReference(folder + "files");
                string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(filename);
                CloudBlockBlob cloudBlockBlob = Img.GetBlockBlobReference(imageName);
                CloudBlobClient blobClient1 = cloudStorageAccount.CreateCloudBlobClient();
                using (var fs = File.OpenRead(obj))
                {
                    cloudBlockBlob.UploadFromStream(fs);
                }

                string imageFullPath = container.Uri.ToString();
                ViewState["BlobPath"] = imageFullPath;

            }
            if (i == 3)
            {
                CloudBlobDirectory Img = container.GetDirectoryReference(folder + "music");
                string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(filename);
                CloudBlockBlob cloudBlockBlob = Img.GetBlockBlobReference(imageName);
                CloudBlobClient blobClient1 = cloudStorageAccount.CreateCloudBlobClient();
                using (var fs = File.OpenRead(obj))
                {
                    cloudBlockBlob.UploadFromStream(fs);
                }

                string imageFullPath = container.Uri.ToString();
                ViewState["BlobPath"] = imageFullPath;

            }

        }
    }
    #endregion
    #region Partner or Client Click foont end
    protected void btn_postHidden_Click(object sender, EventArgs e)
    {
        // Response.Redirect("~/PartnerLogin.aspx");
        Session["Client"] = "Partner";
        SignIn();
    }

    protected void btn_clientpostHidden_Click(object sender, EventArgs e)
    {
        Session["Client"] = "Client";
        ClientSignIn();
    }
    public static async void DownloadPageAsync(string input)
    {
        // ... Use HttpClient.
        using (HttpClient client = new HttpClient())
        using (HttpResponseMessage response = await client.GetAsync(input))
        using (HttpContent content = response.Content)
        {
            //string result = await content.ReadAsStringAsync(input);

        }

    }
    #endregion



    #region Declare List Of Objects
    public static string getOperatinSystemDetails(string browserDetails)
    {
        string deviceType = "";
        try
        {
            switch (browserDetails.Substring(browserDetails.LastIndexOf("Windows NT") + 11, 3).Trim())
            {
                case "6.2":
                    return "Windows 8";
                case "6.1":
                    return "Windows 7";
                case "6.0":
                    return "Windows Vista";
                case "5.2":
                    return "Windows XP 64-Bit Edition";
                case "5.1":
                    return "Windows XP";
                case "5.0":
                    return "Windows 2000";
                default:
                    return browserDetails.Substring(browserDetails.LastIndexOf("Windows NT"), 14);
            }


            if (browserDetails.Contains("ipod") || browserDetails.Contains("iphone"))
                deviceType = "ipod";
            return deviceType;

            if (browserDetails.Contains("android"))
                deviceType = "android";
            return deviceType;

            if (browserDetails.Contains("opera mobi"))
                deviceType = "opera mobi";
            return deviceType;

            if (browserDetails.Contains("windows phone os") && browserDetails.Contains("iemobile"))
                deviceType = "windows phone os";
            return deviceType;

            if (browserDetails.Contains("fennec"))
                deviceType = "fennec";
            return deviceType;

        }
        catch
        {
            if (browserDetails.Length > 149)
                return browserDetails.Substring(0, 149);
            else
                return browserDetails;
        }
    }
    public static IPAddress GetDefaultGateway()
    {
        var card = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault();
        if (card == null) return null;
        var address = card.GetIPProperties().GatewayAddresses.FirstOrDefault();
        if (address != null)
        {
            return address.Address;

        }
        return null;
    }


    #endregion

    protected void btnAdmin_Click(object sender, EventArgs e)
    {
        Session["Client"] = "Admin";
        AdminSignIn();
    }
    public void AdminSignIn()
    {
        if (!Request.IsAuthenticated)
        {
            // To execute a policy, you simply need to trigger an OWIN challenge.
            // You can indicate which policy to use by specifying the policy id as the AuthenticationType
            HttpContext.Current.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties()
                {
                    RedirectUri = "/"
                }, Startup.AdminSignInPolicyId);
        }
    }
    //gggggghh

}

Comments

Popular posts from this blog

FAQ BIND

Create Schema Using C# Asp .Net Dynamically.

resgination mail