Tuesday, 26 January 2016

Prevent simultaneous logins by a single User ID

You can prevent simultaneous logins by a single User ID.
Use the below coding in your c# web application.
in Login.aspx 
function ShowErrorMsg() 
<input type="hidden" runat="server" id="hdnMsg" /> 
in Login.aspx.cs
private bool isAlreadyLogged(string sUserId, string sPwd)
       string sKey = sUserId + sPwd;
       string sUser = Convert.ToString(Cache[sKey]);
       if (sUser == null || sUser == String.Empty)             
           // No Cache item, so session is either expired or user is new sign-on
           // Set the cache item and Session hit-test for this user---
           TimeSpan SessTimeOut = new TimeSpan(0, 0, HttpContext.Current.Session.Timeout, 0, 0);
           HttpContext.Current.Cache.Insert(sKey, sKey, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null);
           Session["LoginInfo"] = sUserId + sPwd;
           return false;
           return true;
protected void btnLogin_Click(object sender, EventArgs e)
     if ("Password is correct")
     {  // After checking Login Credentials validation against your DB
        if (isAlreadyLogged(sUserId, sPwd))
             hdnMsg.Value = "User already Logged IN, through other browser/machine. ";
             ClientScript.RegisterStartupScript(GetType(), "Msg1", "ShowErrorMsg();", true);
             Response.Redirect("Index.html", false);
     hdnMsg.Value = "User Id or Password not valid!.";
     ClientScript.RegisterStartupScript(GetType(), "Msg1", "ShowErrorMsg();", true);
in Logout.aspx.cs 
protected void Page_Load(object sender, EventArgs e)

     Session["LoginInfo"] = "";
in Index.aspx (Main Page)
If user close the browser by clicking on ‘X’ button then our Logout page should call, Then only the Cache will erase and the same user can login again, otherwise Cache will not allow the user to login again. For that purpose,
Note: Make sure to allow popup blocker.
<script language="Javascript" type="text/javascript">
function GotoLogout() {
    window.open('Logout.aspx', 'mywindow', 'location=1,status=1,scrollbars=1, width=1,height=1');           
<body onbeforeunload="GotoLogout();">

Thursday, 22 October 2015

Sending Mail through programming using Gmail Account

Use the below coding in your c# web application.
public void SendMailTo()
                SmtpClient client = new SmtpClient("smtp.gmail.com");
                client.Port = Convert.ToInt16(587);

                client.EnableSsl = true;
                client.Timeout = 100000;
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential("YourMailId@gmail.com", "Your Password");

                MailMessage msg = new MailMessage();
                msg.IsBodyHtml = true;

                msg.From = new MailAddress("YourMailId@gmail.com");
                msg.Subject = "Subject";

                string sBody = "Dear Sir/Mam";
                sBody += "<br/><br/>Your Message";

                msg.Body = sBody;
            catch (Exception ex)

Settings in Gmail Account:
Enable your Pop settings.

Monday, 10 August 2015

Jquery Auto complete text box in asp.net

string sSql = string.Format("SELECT CurrencyCode + ' (' + CountryName + ')' as CurrencyCode, CurrencySeqId FROM Tbl_Currencies WHERE CurrencyCode LIKE '%{0}%' OR CountryName LIKE '%{0}%' Order By CurrencyCode ", sCurrency);

In YourPage.aspx.cs
public static List<string> GetCurrency(string sCurrency)
      List<string> Currency = new List<string>();
      DataTable dt = null;
//Use that query and get the data from your DB (my Method name is “GetCurrencyForAuto”)
      dt = GetCurrencyForAuto(sCurrency);

      for (int i = 0; i < dt.Rows.Count; i++)
Currency.Add(string.Format("{0}/{1}", dt.Rows[i][0].ToString(), dt.Rows[i][1].ToString()));
      return Currency;
In YourPage.aspx
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />
            max-height: 250px;
            overflow-y: auto;
            overflow-x: hidden;

<script type="text/javascript">
        $(function () {
                source: function (request, response) {
                    var param = { sCurrency: $('#txtCurrency').val() };
                        url: "YourPage.aspx/GetCurrency",
                        data: JSON.stringify(param),
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    label: item.split('/')[0],
                                    val: item.split('/')[1]
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                select: function (e, i) {
                    $("#<%=hdnCurrencyId.ClientID %>").val(i.item.val);
                minLength: 1 //minLength as 1, it means when ever user enter 1st character in TextBox the AutoComplete method will fire and get its source data.
      <asp:TextBox ID="txtCurrency" runat="server" Text="" Width="100%"></asp:TextBox>

      <input type="hidden" runat="server" id="hdnCurrencyId" />

Out Put: You can search country-wise or currency name-wise in the textbox. and store the CurrencySeqId (PrimaryKey & Auto Number) to hidden box for save purpose.