Country specific phone number validation with ASP.NET

Challenge:

Before few weeks back, I have been assigned a task, Where I need to validate a phone number. Sound simple? Yes it is! But I needed to do it country specific? Now, how it sounds?
Basically, User will have a list of countries to select. And based on his/her country selection he/she will provide phone number and we should validate based on country selection. Sounds challenging? That’s how life should be!
You are also working on such thing and looking for a way to get out of it? Then this post is for you!

Solution:

As per every software engineer’s practice, I started my research and our common friend. Google presented option of using Regex for each country. But it sounded bit complex to me. Then continued my research and found a super hero!
LibPhoneNumberIt’s a library from Google champs to validate phone number (Excerpt from their main page — Google’s common Java, C++ and Javascript library for parsing, formatting, storing and validating international phone numbers. The Java version is optimized for running on smartphones, and is used by the Android framework since 4.0 (Ice Cream Sandwich).)
And after reading this description, It attracted me! (To you as well?). It’s good we found HERO. But how to fit him in our picture? Then after doing bit of a research found this two nice components:

  1. http://phoneformat.com/ — Javascript version of Google’s libphonenumber library
  2. http://libphonenumber.codeplex.com/ – C# port of Google’s libphonenumber

This was a Eureka moment. Just plugged both of this libraries with CustomValidator and you are done! So, here’s how CustomValidator clientside and server-side functions looks like:
Blogs
SUGIN
[sourcecode language=”html”]
<asp:<span class="hiddenSpellError">TextBox ID="txtPhone"  runat="server" />
<asp:<span class="hiddenSpellError">RequiredFieldValidator ID="reqTxtPhone"
runat="server" ErrorMessage="Please enter a phone number" Text="*" ControlToValidate="txtPhone"
></asp:RequiredFieldValidator>
<asp:<span class="hiddenSpellError">CustomValidator ID="custPhoneNumber" runat="server"
OnServerValidate="PhoneNumberValidate"
ErrorMessage="Please enter valid phone number"
Text="*"
ControlToValidate="txtPhone"
ClientValidationFunction="PhoneNumberValidate"
/>
[/sourcecode]

[sourcecode language=”javascript”]
/*
This function will be used to validate
Phone Number client side by CustomValidator
*/
function PhoneNumberValidate(oSrc,args) {
// Call PhoneFormat.JS function which takes Phone Number and Country Code
// in ISO 3166-1 format
var isValidNumberOrNot = isValidNumber(txtPhone.value, ddlcountry.value);
arg.IsValid = isValidNumberOrNot;
}
[/sourcecode]
[sourcecode language=”csharp”]
/// <summary>
/// This function will be used to validate
/// Phone Number server side by CustomValidator
/// </summary>
/// <param name="source">Source</param>
/// <param name="args">Arguments</param>
protected void PhoneNumberValidate(object source, ServerValidateEventArgs args)
{
PhoneNumberUtil phoneUtil = PhoneNumberUtil.Instance;
// TODO : EXCEPTION HANDLING
string countryCode = ddlcountry.SelectedItem.Value
if (string.IsNullOrEmpty(countryCode))
{
args.IsValid = false;
}
else
{
PhoneNumber phoneNumber = phoneUtil.Parse(txtPhone.Text, countryCode);
bool isValidNumber = phoneNumber.IsValidNumber;
args.IsValid = isValidNumber;
}
}
</span></span></span>
[/sourcecode]
Just a note : LibPhoneNumber accepts country code in ISO 3166-1 format. But if you’ve drop down Text and Value both in full form e.g. “India” and you need to pass it as “IN” and If it’s not possible to do any change at your DropDown value level then you can use function, Which has been submitted at — https://github.com/albeebe/phoneformat.js/issues/9 It converts CountryName to CountryCode
Happy Phone Number Validation! 🙂

Bootstrap with ASP.NET Basics and learnings

Challenge:

Howdy Folks, Sorry for being away from you for so long. But was occupied with lot of other things. But now, I’m here to share my learnings with you.
Before couple of weeks back, I’ve to create one functionality to make user’s task easy. I was clear with back-end code. And to make UI intuitive, I thought to use Bootstrap (If you are new to bootstrap, then I would recommend you to take a moment and give it a read here : http://en.wikipedia.org/wiki/Bootstrap_%28front-end_framework%29 and http://getbootstrap.com/)
Long story short, Bootstrap is a framework for creating UI more intuitive rapidly! Developed by Twitter champs!
And If you know Bootstrap, you must be knowing that how easy it is to integrate bootstrap with your application. And yes, you are right it is. But while working on it, I found few challenges and learnt something which I thought to share with you!
Let’s go!

Solution:

If you are new to bootstrap, and looking for a way to integrate it with your ASP.NET application, then following are a good read to do so:
If you are using VS 2013 then you don’t have to worry. Because MS guys has integrated bootstrap within it.
http://techcrunch.com/2013/06/27/microsoft-adds-bootstrap-support-to-visual-studio-2013/
http://www.asp.net/visual-studio/overview/2013/creating-web-projects-in-visual-studio#bootstrap
But if you are using VS < 2013 then this posts will surely help you:
http://geekswithblogs.net/JeremyMorgan/archive/2012/09/18/how-to-use-twitter-bootstrap-on-an-asp.net-website.aspx
http://www.mytecbits.com/microsoft/dot-net/bootstrap-3-0-0-with-asp-net-web-forms
http://elbruno.com/2013/10/02/vs2013-howto-create-a-website-project-in-visual-studio-using-bootstrap/
So, have you tried it? Looks simple, Correct? Till this point of time, everything was simple. But Life is not as simple as it seems to be!
So here are my learnings:

  1. Dismissable alerts : When I tried to use it (http://getbootstrap.com/components/#alerts-dismissable). It didn’t worked. Then figured out that it needs Jquery reference on a page. So, If you are facing same challenge, give it a try! Or if you are going to use first time, don’t do such mistake 🙂
  2. Modal : The default example of Modal given in documentation, didn’t worked for me. Then this tutorial helped me : http://www.w3resource.com/twitter-bootstrap/modals-tutorial.php
  3. Width of Modal Dialog : If you would like to change width of a modal dialog then here’s a way to do it: http://stackoverflow.com/questions/10169432/how-can-i-change-the-default-width-of-a-twitter-bootstrap-modal-box
  4. RequiredFieldValidation and Validation and State : Wanted to apply styling as shown here: http://getbootstrap.com/css/#forms-control-validation

Initially tried with RequiredFieldValidator. But due to it’s complexity avoided doing so. Then used CustomValidator, Here’s how ClientValidationFunction function looks like:
[sourcecode language=”javascript”]
function ValidateALTText(oSrc, args) {
var isValid = false;
// label label-warning
isValid = args.Value.trim();
if (isValid) {
$("#" + oSrc.id).prev(".form-control").parent().removeClass("has-error");
}
else {
$("#" + oSrc.id).prev(".form-control").parent().addClass("has-error");
}
args.IsValid = isValid;
}
[/sourcecode]

  1. Jquery Plugins : Cool, Jquey Plugins which has been designed to use with Bootstrap
    1. Wizard : Would like to create Wizard? http://vadimg.com/twitter-bootstrap-wizard-example/
    2. Confirm, Alert, Custom Dialog : If you would like to take a confirmation from user before doing postback then go for http://bootboxjs.com and if you are facing issue while showing confirmation box and doing postback then this thread will surely help you : http://stackoverflow.com/questions/20389205/bootbox-with-jquery-and-bootstrap-with-a-net-page-no-working/21433099#21433099
    3. FileStyle : Change look and feel of your file input box : http://markusslima.github.io/bootstrap-filestyle/

Found it useful? You have your own set of learnings? Why don’t you share it with all of us?
Happy Bootstraping! 🙂
Good reads:

  1. Twitter Bootstrap Tutorial : http://www.w3resource.com/twitter-bootstrap/tutorial.php
  2. The original list of resources and plugins for Bootstrap : http://bootsnipp.com/resources

 

JQuery, JSON with ASP.NET notes

Challenge:

Before couple of weeks back, was trying to implement Facebook like live updates in ASP.NET and JSON and while doing that, faced couple of challenges. Which I thought you may find interesting!
Would like to share challenges/tasks with you. So, you can also get benefited by it when you face them!

Solution:

  • Convert Generic List to JSON : Had a generic list, which comes from DB, and needs to pass it on to UI layer, in a JSON format, used System.Web.Script.Serialization.JavaScriptSerializer class for this [using System.Web.Script.Serialization]:

[sourcecode language=”csharp”]
// ……….
List<UserUpdate> userUpdates = new List();
while (sqlDataReader.Read())
{
UserUpdate userUpdate = new UserUpdate();
userUpdate.UserID = Convert.ToInt32(sqlDataReader["ID"]);
userUpdate.UpdateMessage = Convert.ToString(sqlDataReader["UpdateMessage"]);
userUpdates.Add(userUpdate);
}
JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();
string JSONString = javascriptSerializer.Serialize(userUpdates);
return JSONString;
[/sourcecode]
Just a note : If you are doing Response.Write then please do change your page’s content-type to JSON — Response.ContentType = “application/json; charset=utf-8”;

  • After every 2 second update right side data using AJAX and JSON : There will be a sidebar sitting in right side of a page and after every X seconds, it should get updated with latest updates from application:

To do this, added one UL tag on page, which will hold all data:
<ul id=”user-updates”>
</ul>
Added JavaScript on page, which checks for update every 2 second and prep ends to UL tag:
[sourcecode language=”javascript”]
<script type="text/javascript">
var url = "UserUpdates.aspx"; //This page returns JSON
var userID;
$(document).ready(function() {
// Initially all data
$.getJSON(url, function(result) {
$.each(result, function(i, field) {
userID = field.UserID;
$("
<ul>
<li><i class=’icon-text-width’>" + field.UpdateMessage + "</li>
</ul>
")
.hide().prependTo(‘#user-updates’).slideDown("slow");
});
});
setInterval(function() {
$.getJSON(url, { UID: userID }, function(result) {
$.each(result, function(i, field) {
userID = field.UserID;
$("<li><i class=’icon-text-width’></i><span>" + field.UpdateMessage + "</span> </li>")
.hide().prependTo(‘#user-updates’).slideDown("slow");
});
});
}, 2000);
});
[/sourcecode]

  • JQUERY Prepending an LI to an UL with Animation — When any new LI gets added to UL, it should come as an Animation – and invested, lot of time to achieve this requirement and finally, following link worked! [Thanks!]

http://stackoverflow.com/questions/2883154/jquery-prepending-an-li-to-an-ul-with-animation

  • Rather than showing DateTime wanted to say “Two days ago/2 seconds ago” etc. message : – Following threads helped to do so! [Thanks!]

C# solution : http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time
JavaScript based solution : http://www.aspdotnet-suresh.com/2012/02/jquery-display-time-in-facebook-twitter.html
Simple, yet powerful? Learnt a lot!
I would suggest all of you, to take a simple project for fun and try to implement it, Trust me, It will be full of fun! And you will learn a lot, and most IMP. these learnings will not go away from you for a long time. Because you learnt it with fun! Have you forgotten how to play Cricket? How to Ride a bicycle etc.? Because you learnt it funny way not in a pressurized way! 🙂
Also, If possible do blog your learnings!
Happy Coding! 🙂

Object dosen't support this property or method with showModalDialog

Challenge:

We’re trying to open Modal Window from Modal Window on button click which is inside update panel:
[sourcecode language=”csharp”]
protected void Button1_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(Button1, page.GetType(), "OpenModalDialog", "<script type=text/javascript>window.showModalDialog(‘http://www.gooogle.com, null, ‘dialogHeight:100px;dialogWidth:280px;status:no’); </script>", false);
}
[/sourcecode]
But it was giving an error Object dosen’t support this property or method

Solution:

Pls  check that pop-up blocker is not active. [Tools | Pop-Up Blocker|Turn-off Pop-up Blocker].