Auto Logout after 20 minutes of inactive | Asp.net, Javascript, Jquery

By // No comments:

Auto-Logout-after-20min-of-inactive-using-Asp.net-Javascript-Jquery

Introduction

In this article I will explain how to auto logout using JQuery in asp.net after 20 mins and redirect to login page when user is inactive. We often see banking sites if we stay inactive or ideal for sometime they will automatically show alert and logout. We are using the same concept with simple method by using JQuery.

Auto logout Code


jQuery(document).ready(function () {
//---> auto logout on 20mins -- codeview.in
var initialTime = new Date();
var intervalId = setInterval(function Redirect() {
var minutes = Math.abs((initialTime - new Date()) / 1000 / 60);
//console.log(minutes);
if (minutes > 20) {
clearInterval(intervalId);
alert('Your session is expired, please login again.');
window.location.href='<%= ResolveUrl("Logout.aspx") %>';
}
}, 60000); //1 min

$(document).delegate("#form1", "click change", function () {
initialTime = new Date();
});
//<-- end
});
 

Code Explanation

1) Place the above code in Master Page, so that in whatever page user is in, code will work.

2) We can also take int  but if the system is locked or idle then numbering count will stop and starts when system is unlcoked, so to avoid that We took new Date() instead of int


var initialTime = new Date();

3) We used setInterval to loop every minute and clearInterval  to stop when time reached above 20 mins

4)In masterpage form will be there, give an id to that and use that in delegate to tell restart the time whenever any click or change happens. You can even add mouse hover etc.. based on your requirements.


<form id="form1" runat="server">...</form>

Conclusion

I took 20 mins as the default HttpSessionState.Timeout expiration period is 20 Minutes, if you want you can increase and change these values accordingly..

Hope this article is clear enough. Feel free to comment below if you got any doubts.

How To Track An Email In ASP.NET using IHttpModule

By // 2 comments:


In this article i will explain, how to track an Email if it is opened or read by the user.We can achieve this by sending a small beacon image with the Email.


Introduction


We will send an Email by embedding a blank image with a key.We will implement a HttpModule so that when a user opens the Email,then it will request for the original image and we will send it back.At that time we will record that request and save it in Database or log it for our reference to check at what time and how many times the email is opened.


Creating Application

Lets create a web application.

creating-web-application

Open Visual Studio.Select File >> New >> Website

empty-website

Select Visual C# on left pane and select ASP.NET Empty Web Site on right pane.

Select Web Location at the bottom and select path folder by giving a name to the application, I'm giving 'EmailTracking' as application name.

empty-web-application-solution

Click OK and your new empty web application solution is created.


Sending Email

Add web form with the name EmailTracking

adding-webform-to-solution webform-name

We will add a button to the web form to send an email and a label to display messages.

Add some style to the button,so that it looks better

on button click,we will write the code to send an email.In the Email, we will attach an image.

<asp:button onclick="btnTestEmail_Click" id="btnTestEmail" runat="server" text="Test Email Tracking" cssclass="greenbtn" />
string subject = "This is test mail";
string toEmail = "receiver@codeview.in";//receiver email adrress
string fromEmail = "sender@codeview.in";//sender email adrress

string content = "Hello User, <br><br>";
content += "This is a test Email<br><br>";
content += "Thank you for visiting www.codeview.in \n  <br><br>";
content += @"<img src=""http://localhost:53028/images/<keyvalue>.aspx"" />";//your own url
string keyValue = "codeview"; //generate unique key here
content = content.Replace("<keyvalue>", keyValue);

new Utility().SendEmail(fromEmail, toEmail, subject, content, true);
lbl.Text = "Mail Sent Successfully";
lbl.ForeColor = System.Drawing.Color.Green;

In the above code,I’m generating a unique key and requesting for an codeview.aspx file from the images folder for the image src, where it doesn't even exist.Then, instead of returning a 404 or file not found error, we will send back the image which we we already got using HttpModule.


Here is the complete code of EmailTracking.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="EmailTracking.aspx.cs" Inherits="EmailTracking" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
        .greenbtn {
            color: #FFFFFF;
            background-color: #0b7348;
            border: 1px solid transparent;
            white-space: nowrap;
            padding: 6px 12px;
            font-size: 14px;
            line-height: 1.42857;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
<div>
<asp:Button ID="btnTestEmail" runat="server" Text="Test Email Tracking" CssClass="greenbtn" 

OnClick="btnTestEmail_Click" />
            <asp:Label ID="lbl" runat="server"/>
        </div>
</form>
</body>
</html>
using System;

public partial class EmailTracking : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnTestEmail_Click(object sender, EventArgs e)
    {
        try
        {
            string subject = "This is test mail";
	    string toEmail = "receiver@codeview.in";//receiver email adrress
	    string fromEmail = "sender@codeview.in";//sender email adrress

	    string content = "Hello User, <br><br>";
	    content += "This is a test Email<br><br>";
	    content += "Thank you for visiting www.codeview.in \n  <br><br>";
	    content += @"<img src=""http://localhost:53028/images/<keyvalue>.aspx"" />";//your own url
	    string keyValue = "codeview"; //generate unique key here
	    content = content.Replace("<keyvalue>", keyValue);

	    new Utility().SendEmail(fromEmail, toEmail, subject, content, true);
	    lbl.Text = "Mail Sent Successfully";
	    lbl.ForeColor = System.Drawing.Color.Green;
        }
        catch (Exception ex)
        {
            lbl.Text = ex.Message;
            lbl.ForeColor = System.Drawing.Color.Red;
        }
    }
}

Adding HTTP Module

Right click on solution folder and add an App_Code folder



Right click on App_Code folder and add a new class file with name 'ImageTracker'


Add the below lines of code, so that you class file should look like the same


using System;
using System.Web;

/// 
/// Summary description for ImageTracker
/// 
public class ImageTracker : IHttpModule
{
    public void Dispose()
    {

    }

    public void Init(HttpApplication context)
    {

    }    
}

In the Init() method, we will register the event GetImage_BeginRequest(). Now,Our code will change to


public void Init(HttpApplication context)
{
   context.BeginRequest += new System.EventHandler(GetImage_BeginRequest);
}

public void GetImage_BeginRequest(object sender, System.EventArgs args)
{

}

Now we will register the HttpModule to the web.config:


<system.webserver>    
    <modules>
      <add type="ImageTracker" name="ImageTracker" />
    </modules>   
  </system.webserver> 

Now in GetImage_BeginRequest(), we will add our code to validate and return the image, which should look like this


public void GetImage_BeginRequest(object sender, System.EventArgs args)
{
        //cast the sender to a HttpApplication object
        System.Web.HttpApplication application = (System.Web.HttpApplication)sender;

        string url = application.Request.Path; //get the url path        
        string pattern = @&quot;/images/(?<key>.*)\.aspx&quot;;

        //create the regex to match for beacon images
        Regex r = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
        if (r.IsMatch(url))
        {
            MatchCollection mc = r.Matches(url);
            if ((mc != null) &amp;&amp; (mc.Count &gt; 0))
            {
                string key = (mc[0].Groups[&quot;key&quot;].Value);
                //SaveToDB(key);               
                new Utility().writeLog(&quot;Mail Read - &quot; + key + &quot; : &quot; + DateTime.Now.ToString());
            }

            //now send the REAL image to the client
            application.Response.ContentType = &quot;image/gif&quot;;
            application.Response.WriteFile(application.Request.MapPath(logo));//logoFile is defined above

            //end the response
            application.Response.End();
        }
}

Add an Images folder to the solution and add the logo to that which we need to send.Add a notepad also to the solution,so that we can log.



Here is the complete code


using System;
using System.Text.RegularExpressions;
using System.Web;

/// <summary>
/// Summary description for ImageTracker
/// </summary>
public class ImageTracker : IHttpModule
{
    string logo = &quot;~/images/codeview.png&quot;;

    public void Dispose()
    {

    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new System.EventHandler(GetImage_BeginRequest);
    }

    public void GetImage_BeginRequest(object sender, System.EventArgs args)
    {
        //cast the sender to a HttpApplication object
        System.Web.HttpApplication application = (System.Web.HttpApplication)sender;

        string url = application.Request.Path; //get the url path        
        string pattern = @&quot;/images/(?<key>.*)\.aspx&quot;;

        //create the regex to match for beacon images
        Regex r = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
        if (r.IsMatch(url))
        {
            MatchCollection mc = r.Matches(url);
            if ((mc != null) &amp;&amp; (mc.Count &gt; 0))
            {
                string key = (mc[0].Groups[&quot;key&quot;].Value);
                //SaveToDB(key);               
                new Utility().writeLog(&quot;Mail Read - &quot; + key + &quot; : &quot; + DateTime.Now.ToString());
            }

            //now send the REAL image to the client
            application.Response.ContentType = &quot;image/gif&quot;;
            application.Response.WriteFile(application.Request.MapPath(logo));

            //end the response
            application.Response.End();
        }
    }
}

Output

As our complete code is ready now,lets send an email to test.


When the Email is opened, then from the image src 'http://localhost:53028/images/codeview.aspx' a request is made to our application and GetImage_BeginRequest() is called. In that we will validate for the file type and our Regular Expression will grab the key name which is 'codeview'. That key is then used to save in our database file.Here rather than saving, i will log them in a text file with key name and time. Once the tracking is completed we will send our own logo.




This will work on all major Email clients.Tested on Yahoo,Gmail and MSN. In Gmail, it will work only if you place the image in a public domain folder.


Hope this article is clear enough.Feel free to comment below if you got any doubts.


Reference : www.aspnetemail.com

How To Reseed Identity After Deleting Records In SQL Server

By // No comments:

In this article i will explain, how to Reseed Identity after deleting records In SQL Server

Creating Table and Add Rows

Lets create a table with name 'Groups'.

Lets add some rows to table and check the identity, [group_id] is incrementing by +1 value

table-creation-sql-server

Delete Rows

Now, Im deleting rows from [group_id] 5 to 13.

deleting-rows

After deleting the rows, now im adding some rows.

adding-rows

In the above pic,check the [group_id] is now 14 and is incrementing by +1 value.This is because we already deleted the rows till 13 and it is still counting from the next number.

Reseed

To make the [group_id] to start from number 5, we need to Reseed that number by using the below code

DBCC CHECKIDENT ('[groups]', RESEED, 4);

In the above code i have given the table name and telling to Reseed from number 4, so that it will start from 5

Result

table-creation-sql-server

How To Send Email Using SMTP in C#

By // 3 comments:
How_To_Send_Email_Using_SMTP_in_C#

In this article i will explain how to send an Email using SMTP in ASP.NET C#.


SMTP (Simple Mail Transfer Protocol) is a reliable protocol which handles exchange of messages between Email servers. When you send Email , your Email client sends it to Email server and contacts the recipient mail server using SMTP client.


Lets proceed and send an Email.

Add SMTP details to web.config

Add the below code to your web.config file and fill all the values,with your own SMTP details.If your SMTP got a port number then fill it else leave it as it is.

<appSettings>    
    <!-- SMTP Details -->
    <add key="SMTPHost" value="YOUR SMTP HOST NAME"/>
    <add key="SMTPUserID" value="YOUR SMTP USER ID"/>
    <add key="SMTPPwd" value="YOUR SMTP USER PASSWORD"/>
    <add key="SMTPPort" value=""/>
    <add key="SMTPDomain" value="YOUR SMTP DOMAIN"/>
</appSettings>

SMTP Code

Use the below SendEmail method of SMTP code which will be used to send Emails.

using System;
using System.Net.Mail;
using System.Configuration;

public void SendEmail(string fromEmail, string fromName, string toEmail, string subject, string content, bool isHTML)
    {
 string SmtpServer = Convert.ToString(ConfigurationManager.AppSettings["SMTPHost"]);
 string SmtpUserID = Convert.ToString(ConfigurationManager.AppSettings["SMTPUserID"]);
 string SmtpPwd = Convert.ToString(ConfigurationManager.AppSettings["SMTPPwd"]);
 string SmtpPort = Convert.ToString(ConfigurationManager.AppSettings["SMTPPort"]);
        string SmtpDomain = Convert.ToString(ConfigurationManager.AppSettings["SMTPDomain"]);

        MailMessage mm = new MailMessage();
        mm.From = new System.Net.Mail.MailAddress(fromEmail, fromName);
        mm.To.Add(toEmail);
        mm.Subject = subject;
        mm.Body = content;
        mm.IsBodyHtml = isHTML;
        
        System.Net.Mail.SmtpClient mailClient;
        if (string.IsNullOrEmpty(SmtpPort.Trim()))
        {
            mailClient = new System.Net.Mail.SmtpClient(SmtpServer);
        }
        else
        {
            mailClient = new System.Net.Mail.SmtpClient(SmtpServer, Convert.ToInt32(SmtpPort));
        }

        System.Net.NetworkCredential AuthenticationInfo;

        AuthenticationInfo = new System.Net.NetworkCredential(SmtpUserID, SmtpPwd);

        mailClient.UseDefaultCredentials = false;
        mailClient.Credentials = AuthenticationInfo;
        mailClient.EnableSsl = false;
        mailClient.Send(mm);
    }


Send Email

Add a button to send an Email and label to display success message on aspx page.

<asp:button onclick="btnTestEmail_Click" id="btnTestEmail" cssclass="greenbtn" text="Send Email" runat="server" />
<asp:label id="lbl" runat="server" />

On button click event prepare Email body, give subject and send an Email to test if it is working.

protected void btnTestEmail_Click(object sender, EventArgs e)
    {
        try
        {
            string subject = "Test Mail";
            string content = "Hello User, 

"; content += "This is a test Email"; content += "Thank you for visiting www.codeview.in \n

"; SendEmail("sender email adrress", "sender name", "receiver email address", subject, content, true); lbl.Text = "Mail Sent Successfully"; lbl.ForeColor = System.Drawing.Color.Green; } catch (Exception ex) { lbl.Text = ex.Message; lbl.ForeColor = System.Drawing.Color.Red; } }

Result

Send_Email_Using_SMTP_in_Csharp_success_msg Send_Email_Using_SMTP_in_Csharp_received_mail

Hope this article is clear enough.Feel free to comment below if you got any doubts.

How To Create Log File in C#

By // No comments:
Creating+A+Log+File+Using+C#

In this article i will explain how to create a simple text based log file in c#.

A log file can be of any type based on your requirements.You can log user activity, errors captured, log in times..etc. The below code creates the text file if it does not exist at the path we provided and appends the log information to the file.


Lets proceed and create the Log file.

Step 1 :

We will add the file path,where we want the Log file to be created in web.config file.

<appSettings>
    <!-- Log path -->  
    <add key="LogfilePath" value="D:\CodeView\Files\ImageTrack.log"/> 
  </appSettings>

Step 2 :

Using the Stream Writer, we will check if the Log file exists or not.If it doesn't exist we will create one else we will append the text to the Log file.

public void writeLog(string strValue)
    {
        try
        {
            //Logfile
            string path = System.Configuration.ConfigurationManager.AppSettings["LogfilePath"];
            StreamWriter sw;
            if (!File.Exists(path))
            { sw = File.CreateText(path); }
            else
            { sw = File.AppendText(path); }

            LogWrite(strValue, sw);

            sw.Flush();
            sw.Close();
        }
        catch (Exception ex)
        {

        }
    }

Step 3 :

We can style the Log file by our requirements on what to write and how to write.

private static void LogWrite(string logMessage, StreamWriter w)
    {
        w.WriteLine("{0}", logMessage);
        w.WriteLine("----------------------------------------");
    }

Call Method

Now lets call the writeLog() method to create the Log file.

protected void Page_Load(object sender, EventArgs e)
    {
string key = "codeview";
writeLog("Mail Read - " + key + " : " + DateTime.Now.ToString());
}

Result

log+file

Hope this article is clear enough.Feel free to comment below if you got any doubts.

Get IPAddress Using C# ASP.Net

By // 1 comment:

In this article i will explain how to get your local IP Address using asp.net c#.

First lets take button for click event and a label to display the ip address

<asp:Button ID="btnIpAddress" runat="server" OnClick="btnIpAddress_Click" Text="Get IP Address" Font-Size="X-Large"/>
<asp:Label ID="lblIpAddress" runat="server" Font-Size="XX-Large" ForeColor="Red"></asp:Label>

Now under click event,lets get the ipaddress and bind that to label

using System;
using System.Net;
using System.Net.Sockets;

protected void btnIpAddress_Click(object sender, EventArgs e)
        {            
            lblIpAddress.Text = LocalIPAddress();
        }
public string LocalIPAddress()
        {
            IPHostEntry host;
            string localIP = "";
            host = Dns.GetHostEntry(Dns.GetHostName());
            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    localIP = ip.ToString();
                    break;
                }
            }
            return localIP;
        }

Another simple, recommended and most effective way is to use below method


public string LocalIPAddress()
        {
            string localIP = Request.ServerVariables["REMOTE_ADDR"].ToString();
            return localIP;
        }

Demo:

HTTP Error 500.23 - Internal Server Error

By // No comments:

Recently i faced the above error when i tried to open a web page.


Error Details:

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.


Most likely causes:

  • This application defines configuration in the system.web/httpHandlers section.Check if your web.config file contains any httpHandlers.

Things you can try:

  • Migrate the configuration to the system.webServer/handlers section. You can do so manually or by using AppCmd from the command line. For example, from the IIS Express install directory, run appcmd migrate config "Default Web Site/". Using AppCmd to migrate your application will enable it to work in Integrated mode. It will continue to work in Classic mode and on previous versions of IIS.
  • If you are certain that it is OK to ignore this error, it can be disabled by setting system.webServer/validation@validateIntegratedModeConfiguration to false.
  • Alternatively, switch the application to a Classic mode application pool. For example, from the IIS Express install directory, run appcmd set app "Default Web Site/" /applicationPool:"Clr4ClassicAppPool". Only do this if you are unable to migrate your application.

Solution:

Add the below lines of code in web.config file Configuration section, so that this will ignore that error.

<configuration>
<system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
  </system.webServer>
</configuration>

Build the solution and run the page now.Hope the error is fixed.

Get Formatted Current Date Using JavaScript

By // No comments:

In this article i will explain how to get todays/current date using javascript

document.getElementById(txtDate).value = getTodaysDate();

function getTodaysDate() {
            var myDate = new Date();
            var year = myDate.getFullYear();
            var month = myDate.getMonth() + 1;
            if (month <= 9)
                month = '0' + month;
            var day = myDate.getDate();
            if (day <= 9)
                day = '0' + day;

            var outdt = month + '/' + day + '/' + year;
            return outdt;
        }

Remove Phone Number Format Using Regex

By // No comments:


In this article i will explain how to remove phone number format using regular expression.


Lets take a phone number format (123) 456-7890 and we need to remove those extra braces, hyphen and extract only the number from it, then we can do this simply by using the below Regex method.

string phoneNumber = "(123) 456-7890";
txtPhone.Text = Regex.Replace(phoneNumber, @"[^\d]", "");

Adding Combobox to Datagrid Dynamically in WPF

By // No comments:

In this article i will explain how to add combo box to data grid dynamically


First,lets take an empty DataGrid.

<DataGrid Name="dataGridRoles" VirtualizingStackPanel.IsVirtualizing="False" Grid.Row="1"  
                      AutoGenerateColumns="False" CanUserAddRows="False" CanUserReorderColumns="False" ScrollViewer.VerticalScrollBarVisibility="Auto"
                      VerticalContentAlignment="Center" HorizontalContentAlignment="Center">            
        </DataGrid>

Now,on code behind in page load write the below lines of code.

In the below code,we are taking a datatemplate and adding the combobox to that.Later we will add the datatemplate to template column and that to datagrid column.

In combo box we will setvalue of NameProperty to give a unique name to each one and also will assign the remain properties,so that it will work like normal combo box.

private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            var vm = (ViewModels.CodeViewModel)DataContext;
            var dataGridTemplateColumn = new DataGridTemplateColumn();
            var dataTemplate = new DataTemplate();
            var comboBox = new FrameworkElementFactory(typeof(ComboBox));

            comboBox.SetValue(NameProperty, new Binding("cc" + dataGridTemplateColumn.Header));
            comboBox.SetValue(ComboBox.ItemsSourceProperty, vm.NameList);//Bind the ObservableCollection list
            comboBox.SetValue(ComboBox.SelectedIndexProperty, 0);
            comboBox.SetValue(ComboBox.DisplayMemberPathProperty, "Name");
            comboBox.AddHandler(ComboBox.SelectionChangedEvent, new SelectionChangedEventHandler(ComboBox_SelectionChanged));

            dataTemplate.VisualTree = comboBox;
            dataGridTemplateColumn.CellTemplate = dataTemplate;
            dataGridRoles.Columns.Add(dataGridTemplateColumn);
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        { 

        }