Count integers from a string in JavaScript

Today’s problem is quite simple, we need to find total numbers from a user input.

Example 1:

Input string: I’m Sunil and 25 years old. I’ve 5.6 years of experience and will be 6 years of experienced in year 2017.

Output: 5

Explanation: 25 will be out first number. Then we have 5.6, in this case we’ll consider it two numbers (this is requirement), but if it is like 56 then this will be 1 number. So by now we have 3 numbers. Fourth one will be 6, and fifth will be 2017.

Example 2:

Input string: +45.6 – 89

Output: 3 (45, 6, 89)

Logic:

Step 1: First of all check for boundary conditions like invalid input; In my code I might not handled all.

Step 2: If input string is good, then add a special character at the end of the string. In my case I have added period (.).

Step 3: Loop and read all the characters of the string one by one.

Step 4: If character is an integer then add it in a variable. If character is not an integer and previously defined variable is not empty that means we have found an integer and current character is a non integer, we need to skip this. So reset the variable that is holding integers and increase the variable that is counting the number of integers.

Code:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Find integer count from a string</title>
    <script type="text/javascript">
        function FindNumbers()
        {
            var someString = document.getElementById('txtInput').value;
            var totalNumbersInString = 0, finalString = '';
            someString += '.';
            for (var i = 0; i < someString.length; ++i)
            {
                if (isNaN(someString[i]) && finalString.length > 0) {
                    totalNumbersInString++;
                    finalString = '';
                }
                else if(!isNaN(someString[i])) {
                    finalString += someString[i];
                }
            }

          document.getElementById('lblOutput').innerHTML = totalNumbersInString;
        }
    </script>
</head>
<body>
    Input string: <input id="txtInput" type="text"> <br>
    <input value="Process" onclick="FindNumbers()" type="submit"><br>
    Output: <div><label id="lblOutput"></label></div>
</body>
</html> 

 

 

 

Show warning in popup just before Session Ends

On many websites we see some popup like you your session will end in 2 mins, specially in Banking website we see this kind of popup. So lets see how can we implement this functionality.

Step 1: Set Timeout in SessionState tag in Web.Config file.

<sessionState mode=”InProccustomProvider=”DefaultSessionProvidertimeout=”3>

Step 2: Add a key in Web.Config in AppSetting for Warning time, time after which you want to show popup.

<appSettings>
    <add key=”SessionTimeOutWarningTimevalue=”2/>
 </appSettings>

Step 3: In your master page, write below script code. The key this of this approach is, as soon as you load a page it sets a Timeout function, so if you are ideal for that much time then it’ll prompt you. And when you reload the page or move to some other page then master page also reloads so it’ll reset the whole code, so whatever time you spent on previous page will not impact on new page. Whole thing will start from zero.

<script type=“text/javascript”>
var sessionTimeOut = <%= Session.Timeout %>;

var sessionWarningTime = “<%=

ConfigurationManager.AppSettings[“SessionTimeOutWarningTime”] %>”;

var timeOutInMiliSeconds = (parseInt(sessionWarningTime ) * 60 * 1000);

setTimeout(“sessionTimeOutShowPopup()”, timeOutInMiliSeconds);

function sessionTimeOutShowPopup() {

alert(“Session will expire in “ +

                       (parseInt(sessionTimeOut) – parseInt(sessionWarningTime ))

          );

};
</script>

Read web.config file in jQuery

In my web.config file there is one key that I need to access to perform some operations on my page. I want to do it using Javascript or jQuery. Below is the sample of key that I’ve in web.config file.

Web.config:

<configuration>
<appSettings>
<add key=”OperationType” value=”ADD” />
</appSettings>
</configuration>

 

Code:

<head runat=”server”>
<title></title>
http://code.jquery.com/jquery-1.9.1.js

$(document).ready(function () {
$(‘#btnCompute’).on(‘click’, function () {
var firstNumber = parseFloat($(‘#txtFirstNumber’).val());
var secondNumber = parseFloat($(‘#txtSecondNumber’).val());
var operationType = ”;
switch (operationType) {
case ‘ADD’: alert(firstNumber + secondNumber); break;
case ‘SUB’: alert(firstNumber – secondNumber); break;
case ‘MUL’: alert(firstNumber * secondNumber); break;
case ‘DIV’: alert(firstNumber / secondNumber); break;
}
});
});

</head>
<body>
<form id=”form1″ runat=”server”>
First Number:
<input type=”text” id=”txtFirstNumber” />
<br />
Second Number:
<input type=”text” id=”txtSecondNumber” />
<br />
<input type=”button” name=”Compute” value=”Compute” id=”btnCompute” />
</form>
</body>

Alert once Page Load is completed in Asp.Net

My friend asked me to alert user once page load is done. There is a simple way to do so, just write a JavaScript function and call it on “onload” of body tag. “onload” will be triggered after all the images and associated resources are loaded completely, that means after whole page load and that’s what we want to do. See below code, how to do it:

xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head>
<title>Test Page</title>
<script type=”text/javascript”>
function onLoadClicked() {
alert(‘Page load is done.’);
}
</script>
</head>
onLoadClicked()”>
<!– HTML CODE –>
</body>
</html>

Zip UnZip files using C#

Hi All, today I found a nice feature of C# to compress and un-compress files. Before starting you have to add one DLL in your application. This DLL is already in your system you just have to reference it.

Add Reference to (~/Windows/Microsoft.NET/assembly/GAC_MSIL/System.IO.Compression.FileSystem/(Your .NET Version)

 

using System;
using System.IO;
using System.IO.Compression;
using System.Web.UI;

public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnZip_Click(object sender, EventArgs e)
{
string strSource = txtSource.Text;
string strDesctination = txtDestination.Text;
if (Validation(strSource, strDesctination, “zip”))
{
try
{
if (File.Exists(strDesctination))
{
File.Delete(strDesctination);
}
ZipFile.CreateFromDirectory(strSource, strDesctination);
ShowMessage(“Zip file is created successfully.”);
}
catch (Exception ex)
{
ShowMessage(“Error!!!”);
}
}
}
protected void btnUnZip_Click(object sender, EventArgs e)
{
string strSource = txtSource.Text;
string strDesctination = txtDestination.Text;
if (Validation(strSource, strDesctination, “unzip”))
{
try
{
if (Directory.Exists(strDesctination))
{
Directory.CreateDirectory(strDesctination);
}
ZipFile.ExtractToDirectory(strSource, strDesctination);
ShowMessage(“File is unzipped successfully.”);
}
catch (Exception ex)
{
ShowMessage(“Error!!!”);
}
}
}

private bool Validation(string source, string destination, string job)
{
if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(destination))
{
ShowMessage(“Please enter valid source and destination path!!!”);
return false;
}
else
{
if (job.Equals(“zip”))
{
if (Directory.Exists(source))
{
return true;
}
}
else if (job.Equals(“unzip”))
{
if (File.Exists(source))
{
return true;
}
}

ShowMessage(“Please enter valid source and destination path!!!”);
return false;
}
}

private void ShowMessage(string message)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), “key”, “alert(‘” + message + “‘)”, true);
}
}

 

 

Item Swapping between Listboxes using jQuery

Hi All, in this article I’ll show how to swap item of listboxes.
1

Code Behind Page:

protected void Page_Load(object sender, EventArgs e)
{
LoadLB();
}

private void LoadLB()
{
for (int i = 0; i < 26; ++i)
{
if (i < 13)
{
lb1.Items.Add(new ListItem(Convert.ToString((char)(65 + i)), (i + 1).ToString()));
}
else
{
lb2.Items.Add(new ListItem(Convert.ToString((char)(65 + i)), (i + 1).ToString()));
}
}
}

Aspx Page:

<asp:Content ID=”Content1″ ContentPlaceHolderID=”HeadContent” runat=”Server”>
Item Swaping from ListBoxes
<style type=”text/css”>
.lb {
min-height: 250px;
min-width: 100px;
float: left;
}

.div {
width: 300px;
}

.div div {
width: 100px;
float: left;
text-align: center;
}

#divBtn {
width: 40px;
float: left;
text-align: center;
}

.button {
width: 30px;
height: 30px;
}
</style>
<script type=”text/javascript”>
$(document).ready(function () {
$(‘[id$=btnAllForward]’).click(function () {
var lb1 = $(‘[id$=lb1]’);
var lb2 = $(‘[id$=lb2]’);
$(lb1).children(‘option’).each(function (index) {
lb2.append(‘<option value=”‘ + $(this).val() + ‘”>’ + $(this).text() + ‘</option>’);
});
lb1.find(‘option’).remove();
});
});

$(document).ready(function () {
$(‘[id$=btnSingleForward]’).click(function () {
var lb1 = $(‘[id$=lb1]’);
var values = lb1.val();
var text = lb1.find(‘option:selected’).text();
var lb2 = $(‘[id$=lb2]’);
for (var i = 0; i < values.length; ++i) {
lb2.append(‘i] + ‘”>’ + text[i] + ”);
}
lb1.find(‘option:selected’).remove();
});
});

$(document).ready(function () {
$(‘[id$=btnSingleBackward]’).click(function () {
var lb2 = $(‘[id$=lb2]’);
var values = lb2.val();
var text = lb2.find(‘option:selected’).text();
var lb1 = $(‘[id$=lb1]’);
for (var i = 0; i < values.length; ++i) {
lb1.append(‘<option value=”‘ + values[i] + ‘”>’ + text[i] + ‘</option>’);
}
lb2.find(‘option:selected’).remove();
});
});

$(document).ready(function () {
$(‘[id$=btnAllBackward]’).click(function () {
var lb1 = $(‘[id$=lb1]’);
var lb2 = $(‘[id$=lb2]’);
$(lb2).children(‘option’).each(function (index) {
lb1.append(‘<option value=”‘ + $(this).val() + ‘”>’ + $(this).text() + ‘</option>’);
});
lb2.find(‘option’).remove();
});
});
</script>
</asp:Content>
<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”Server”>

Item Swaping from ListBoxes

<hr />
<div>
<div>
<asp:ListBox ID=”lb1″ runat=”server” SelectionMode=”Multiple” CssClass=”lb”>
</div>
<div id=”divBtn”>
<input type=”button” id=”btnAllForward” value=”>>” />
<input type=”button” id=”btnSingleForward” value=”>” />
<input type=”button” id=”btnSingleBackward” value=”<” />
<input type=”button” id=”btnAllBackward” value=”<<” />
</div>
<div>
<asp:ListBox ID=”lb2″ runat=”server” SelectionMode=”Multiple” CssClass=”lb”>
</div>
</div>
</asp:Content>