a developer's notes – a semi-technical web development BLOG

January 8, 2014

How to add / remove textbox dynamically with jQuery

Filed under: Javascript / JQuery — Duy Nguyen @ 10:00 pm
Tags: , , , , , , ,

This is a great tutorial!
http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/

<html>
<head>
<title>jQuery add / remove textbox example</title>
 
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
 
<style type="text/css">
	div{
		padding:8px;
	}
</style>
 
</head>
 
<body>
 
<h1>jQuery add / remove textbox example</h1>
 
<script type="text/javascript">
 
$(document).ready(function(){
 
    var counter = 2;
 
    $("#addButton").click(function () {
 
	if(counter>10){
            alert("Only 10 textboxes allow");
            return false;
	}   
 
	var newTextBoxDiv = $(document.createElement('div'))
	     .attr("id", 'TextBoxDiv' + counter);
 
	newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
	      '<input type="text" name="textbox' + counter + 
	      '" id="textbox' + counter + '" value="" >');
 
	newTextBoxDiv.appendTo("#TextBoxesGroup");
 
 
	counter++;
     });
 
     $("#removeButton").click(function () {
	if(counter==1){
          alert("No more textbox to remove");
          return false;
       }   
 
	counter--;
 
        $("#TextBoxDiv" + counter).remove();
 
     });
 
     $("#getButtonValue").click(function () {
 
	var msg = '';
	for(i=1; i<counter; i++){
   	  msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
	}
    	  alert(msg);
     });
  });
</script>
</head><body>
 
<div id='TextBoxesGroup'>
	<div id="TextBoxDiv1">
		<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
	</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
 
</body>
</html>
Advertisements

September 12, 2013

Parsing Google Maps API V3 JSON Response in C# .NET 4

Filed under: ASP.NET MVC,C# — Duy Nguyen @ 10:53 pm
Tags: , , , , , , , , , ,

Here is what you will need to parse responses from Google Maps V3.

Request to the following URL:
http://maps.googleapis.com/maps/api/geocode/json?address=1000+broad+street+road%2c+short+pump%2c+VA+23233&sensor=false

Reponse:

{
   'results' : [
	  {
		 'address_components' : [
			{
			   'long_name' : 'Broad Street Road',
			   'short_name' : 'Broad Street Rd',
			   'types' : [ 'route' ]
			},
			{
			   'long_name' : 'Virginia',
			   'short_name' : 'VA',
			   'types' : [ 'administrative_area_level_1', 'political' ]
			},
			{
			   'long_name' : 'United States',
			   'short_name' : 'US',
			   'types' : [ 'country', 'political' ]
			}
		 ],
		 'formatted_address' : 'Broad Street Road, VA, USA',
		 'geometry' : {
			'bounds' : {
			   'northeast' : {
				  'lat' : 37.6689969,
				  'lng' : -77.64866649999999
			   },
			   'southwest' : {
				  'lat' : 37.662306,
				  'lng' : -77.6778078
			   }
			},
			'location' : {
			   'lat' : 37.6657544,
			   'lng' : -77.66309579999999
			},
			'location_type' : 'GEOMETRIC_CENTER',
			'viewport' : {
			   'northeast' : {
				  'lat' : 37.6689969,
				  'lng' : -77.64866649999999
			   },
			   'southwest' : {
				  'lat' : 37.662306,
				  'lng' : -77.6778078
			   }
			}
		 },
		 'partial_match' : true,
		 'types' : [ 'route' ]
	  }
   ],
   'status' : 'OK'
}

These are the classes you need to define so you can deserialize the json into a type object.

public class GoogleGeoCodeResponse
{
	public results[] results { get; set; }
	public string status { get; set; }
}

public class results
{
	public address_component[] address_components { get; set; }
	public string formatted_address { get; set; }
	public geometry geometry { get; set; }
	public string partial_match { get; set; }
	public string[] types { get; set; }
}

public class geometry
{
	public bounds bounds { get; set; }
	public location location { get; set; }
	public string location_type { get; set; }
	public viewport viewport { get; set; }
}

public class bounds
{
	public northeast northeast { get; set; }
	public southwest southwest { get; set; }
}

public class viewport
{
	public northeast northeast { get; set; }
	public southwest southwest { get; set; }
}

public class northeast : location
{
}

public class southwest : location
{
}

public class location
{
	public decimal lat { get; set; }
	public decimal lng { get; set; }
}

public class address_component
{
	public string long_name { get; set; }
	public string short_name { get; set; }
	public string[] types { get; set; }
}

Here is the code you can use to decode your response.

private void GoogleJsonDecode()
{
	string response = @"
						{
						   'results' : [
							  {
								 'address_components' : [
									{
									   'long_name' : 'Broad Street Road',
									   'short_name' : 'Broad Street Rd',
									   'types' : [ 'route' ]
									},
									{
									   'long_name' : 'Virginia',
									   'short_name' : 'VA',
									   'types' : [ 'administrative_area_level_1', 'political' ]
									},
									{
									   'long_name' : 'United States',
									   'short_name' : 'US',
									   'types' : [ 'country', 'political' ]
									}
								 ],
								 'formatted_address' : 'Broad Street Road, VA, USA',
								 'geometry' : {
									'bounds' : {
									   'northeast' : {
										  'lat' : 37.6689969,
										  'lng' : -77.64866649999999
									   },
									   'southwest' : {
										  'lat' : 37.662306,
										  'lng' : -77.6778078
									   }
									},
									'location' : {
									   'lat' : 37.6657544,
									   'lng' : -77.66309579999999
									},
									'location_type' : 'GEOMETRIC_CENTER',
									'viewport' : {
									   'northeast' : {
										  'lat' : 37.6689969,
										  'lng' : -77.64866649999999
									   },
									   'southwest' : {
										  'lat' : 37.662306,
										  'lng' : -77.6778078
									   }
									}
								 },
								 'partial_match' : true,
								 'types' : [ 'route' ]
							  }
						   ],
						   'status' : 'OK'
						}";

	JavaScriptSerializer jss = new JavaScriptSerializer();
	GoogleGeoCodeResponse test = jss.Deserialize<GoogleGeoCodeResponse>(response);
}

Now you have this!

googleGeoCodeObj

August 27, 2013

ASP.NET MVC Html.DropDownList and Html.DropDownListFor Examples

Html.DropDownList (Webforms Snytax)

View Model:

public class ViewModel
{
	public List<SelectListItem> MyList { get; set; }
}

Controller:


public ActionResult Index()
{
	var model = new ViewModel();            
	GetMyList(model);
	ViewData.Model = model;
	return PartialView("Index");
}

private void GetMyList(ViewModel model)
{
	var cars = (from d in this.Repository.Cars
				 where d.Id == User.Id
				 select d).ToList();
				 
	var listItems = new List<SelectListItem>();
	listItems.Add(new SelectListItem { Text = "-Select Item-", Value = "-1", Selected = true });
	listItems.AddRange(from d in cars
					 select new SelectListItem
					 {
						 Text = d.Desc,
						 Value = d.ID.ToString(),
						 Selected = false
					 });
													 
													 
	model.MyList = listItems;
}

View:

<%= Html.DropDownList("itemsDdlName", Model.MyList , null, null})%>

Html.DropDownListFor (Razor)

View Model:

public class ViewModel
{
	public List<City> Cities { get; set; } 
    public int? CityId { get; set; }
    public List<City> Cities { get; set; }   
}

public class City
{
	public int CityId { get; set; }
	public string CityDescription { get; set; }
}

Controller:


public ActionResult Index()
{
    var model = new ViewModel();           
    GetCities(model);
    ViewData.Model = model;
    return PartialView("Index");
}

private void GetCities(ViewModel m)
{
	using (var db = new CityEntities())
	{
		m.Cities = db.Cities.ToList();
	}
}

View:

@Html.DropDownListFor(model => model.CityId, Model.Cities.ToSelectListItems(x => x.CityDescription, x => x.CityId.ToString(), x => x.CityId == Model.CityId))

April 11, 2013

Parsing a Query String into an array with JavaScript

Filed under: Javascript / JQuery — Duy Nguyen @ 9:50 pm
Tags: , , , , , , , , ,

This brilliant method belongs to Joe Zim’s JavaScript Blog.

Here is the function.

    var parseQueryString = function( queryString ) {
        var params = {}, queries, temp, i, l;
     
        // Split into key/value pairs
        queries = queryString.split("&");
     
        // Convert the array of strings into an object
        for ( i = 0, l = queries.length; i < l; i++ ) {
            temp = queries[i].split('=');
            params[temp[0]] = temp[1];
        }
     
        return params;
    };

Using the function.

   function Test() {
        var qstring = "apple=7sf&orange=242&bananna=47614&cherry=8139";
        var myNewArray = parseQueryString(qstring);
    }

As you can see, you now have an array of all of your query strings!

parseQstring

August 23, 2012

How to offically unlock your AT&T iPhone 4. Was it sucessful even without a confirmation from iTunes?

Filed under: General Tips — Duy Nguyen @ 10:55 pm
Tags: , , , , , , , , , , , , ,

Things you will need:

    You must have an AT&T account in good standing (or know someone who does)
    iPhone must not be tied with an existing contract or have an outstanding bill

Steps:

1. Call or get on a Chat support with an AT&T representative. They will ask for your account information to verify that you have an account with them. If you don’t have one, ask a friend to call for you or to get on the support chat for you.
2. Tell the rep you are traveling and need to do an iPhone unlock.
3. Give the rep your phone’s IMEI number. On the iPhone, Settings >> About. You will see the IMEI number.
4. You will get an email from AT&T with the instructions. Actually getting the instructions is important because that means they have put your IMEI number in their system to authorize the unlock when you do it through iTunes.

Here are the instructions from AT&T:

Thank you for contacting AT&T Customer Care about unlocking your iPhone.
We have reviewed your request and confirmed that you are eligible to have the requested iPhone unlocked.

To complete the unlock, simply:
1. Open iTunes on your Mac or PC and verify that you have internet connectivity.
2. Connect your iPhone using the dock connector to USB cable that came with your iPhone.
3. Backup and restore your iPhone using iTunes .
For information on backup and restore, please visit http://support.apple.com/kb/HT1414.
4. After restoring, your iPhone will be unlocked.

Additional information on unlocking can be found at http://support.apple.com/kb/TS3198.

For questions regarding AT&T’s wireless service and iPhone, please visit the Phone/Device Learning Center.

We thank you for your continued business and look forward to providing you with the best customer service.
Sincerely,

AT&T Customer Care Team

**Make sure you when you RESTORE, YOU MUST RESTORE TO FACTORY SETTINGS! THEN you can restore from the backup you created. You won’t lose any information. My first attempt, I just did a Restore From Backup immediately after the Backup. And it did not work. I verified it didn’t work with AT&T. See the chat log below.

You are supposed to get a confirmation from iTunes indicating that your iPhone is unlocked. But many users, including myself, did not get one. To verify, you have to call AT&T or chat with them online. They are able to check if your phone was indeed unlocked or not. Obviously, you can use a SIM card from another carrier to test with, but I did not have one.

Here is the chat I had with the AT&T rep.

Please wait for a chat representative to respond.
You are now chatting with ‘Amy Budge’
Amy Budge: Thank you for contacting AT&T Live Support Chat!
Amy Budge: I understand you are needing a status update on your request?
Me: No. The request was completed and I was sent instructions on how to Unlock. I need to confirm that it was successful. iTunes did not give me a confirmation that it was unlocked.
Amy Budge: I apologize for any frustration and inconvenience.
Amy Budge: I will be more then happy to help you.
Amy Budge: I appreciate your business and patience. One moment while I access your account.
Amy Budge: The device was unlocked on AT&T’s side. You need to complete a backup and restore in iTunes to complete the unlock.
Me: Yes I did that but there was no success message from iTunes. Are you able to check if it was truly unlocked?
Amy Budge: It is not unlocked.
Me: Back up, and restore from back up? Or restore back to factory settings?
Amy Budge: You need to do the backup and restore again in iTunes.
Amy Budge: You need to back up your information so you do not loose anything. Than hit restore in iTunes.
Amy Budge: You need to have an AT&T sim card in the device. You need to have the latest version of iTunes. You also need to be connected to the Internet while complete the steps.
Me: Yes I have an AT&T sim in right now. Let me download the latest itunes and try again.
Amy Budge: If you need assistance with the backup and restore I can provide the number for Apple.
Me: I have a link to the support documentation from the email I got from At&T.
Amy Budge: Ok.
Me: Can you hang on while the restore completes?
Amy Budge: I sure can.
Me: Is it true that after several unsuccessful attempts, the iPhone will be tied with AT&T for good?
Amy Budge: That is not true with the iPhone.
Me: Thanks for that. That is what the last rep told me.
Amy Budge: Let me re-confirm. I am unaware of this.
Me: ok.
Me: iPhone is retoring iphone software now…
Amy Budge: Ok.
Me: …restoring iphone firmware….
Amy Budge: Ok.
Me: now is asking me to set up my iphone
Me: I will proceed to restore from backup
Amy Budge: Yes.
Me: The restore is complete. And I am back at the home screen on iTunes. Can you check if the unlock was successful?
Me: I did not get any message that says it was successful.
Amy Budge: I have refreshed and it is now successfully unlocked Mr. xxxx.
Me: Thank you for the confirmation. Are you able to send me a confirmation via email?
Amy Budge: I am sorry but I do not have a confirmation email I can send. I can assure it is now successfully unlocked.
Me: Do you know why iTunes did not give me a confirmation?
Me: I will be traveling overseas soon so it is important that it works with another carrier while I am overseas.
Amy Budge: I cannot say why iTunes is not providing confirmation as it is Apple’s software.
Me: Ok thanks.
Amy Budge: I understand and your phone is ready to use with another carrier.
Me: Thanks for checking and your help today.
Amy Budge: You’re Welcome Mr. xxxx! Is there anything else I can do for you today other than assisting with unlocking your iPhone?
Me: That is all.
Amy Budge: Have I resolved your reason for contacting chat today?
Me: Yes.
Amy Budge: Thank you for contacting AT&T Live Support Chat. Have a Wonderful Day!

May 13, 2012

How to setup a FTP server in Windows 7

Filed under: Daily Computing — Duy Nguyen @ 11:34 pm
Tags: , , , , , , , , ,

1. Install IIS : Control Panel (Turn Windows Features on or off)
2. Make sure FTP Server is installed

3. Configure Firewall

(Optional. You only need this if you want to host a website from your home computer.)

4. Create a folder on your file system to store your files that you want to host on your FTP server.

5. Create the FTP site. You can follow this guide. http://www.programmerfish.com/how-to-make-local-ftp-server-in-windows-7/ **I suggest you create a user account on your computer to only allow that user to access your page. If you do this, you will need to enable Basic Authentication and disable Anonymous Authentication.

6. Configure your router so that you can use your FTP site from outside your network.

7. Access your FTP site. FTP://yourPublicIpAddress

Here is a great video you can watch on how to do this.
http://www.youtube.com/watch?v=nWpZkhXnhdshttp://www.youtube.com/watch?v=nWpZkhXnhds

February 8, 2012

Remote Desktop Connection To Your Computer From Outside Your Home

Filed under: Daily Computing,General Tips — Duy Nguyen @ 10:23 pm
Tags: , , , , , , , , , ,

You need to open up port 3389 on your Router and have it forwarded to your specified machine (by IP).

1. Open your Router’s admin page
2. Add port 3389 and specify the machine’s IP you want to allow remote desktop.

See below

Then you will want to register a FREE public domain with https://www.dnsdynamic.org. The reason for this is that your ISP will sporadically change your IP address. Unless you want to keep up with what is your current IP address that your IP gave you, you can just use your public domain and be able to remote to your computer every time.

So just open up the RDP connection and use your new domain.

To enable pings responses on a Linksys E1000, uncheck Filter Anonymous Internet Requests in the Security Tab

Also, make sure your Windows firewall has the ports 3389 open.

You can confirm that port 3389 is open to the public. Go to http://www.yougetsignal.com/tools/open-ports/ and test port 3389.

**To test the remote desktop connection from a computer outside your home network, you should ask a friend to assist. Many corporations and schools block these ports so that you can’t access your home PC while at their facilities.

September 5, 2011

How to write and append to a text file (C# .NET)

Filed under: C# — Duy Nguyen @ 2:33 pm
Tags: , , , , ,

How write to a text file and append more text from another function.


namespace TextFileWriter
{
    public partial class _Default : System.Web.UI.Page
    {
        //Create the StreamWriter object to do the writing
        StreamWriter sw;

        protected void Page_Load(object sender, EventArgs e)
        {
            string driveLetter = "c";
            string folder = "DEV_LOGS";
            string filename = "myFile";
            string fileExtension = ".txt";

            string path = SetFilePath(driveLetter, folder);
            string fullFilePathName = path + "\\" + filename + fileExtension;

            sw = CreateTextFile(fullFilePathName);

            sw.WriteLine("My first line of text");

            function1();

            sw.WriteLine("My third line of text");

            //be sure to close the stream and file or else
            //the file will be locked
            sw.Close();
        }

        public void function1()
        {
            sw.WriteLine("Second line of text");
        }

        public StreamWriter CreateTextFile(string fullFilePathName)
        {
            StreamWriter sw;

            // checks if the file exists
            if (!File.Exists(fullFilePathName))
            {
                sw = File.CreateText(fullFilePathName);
            }
            else
            {
                // file exists, append text to file
                sw = File.AppendText(fullFilePathName);
            }

            return sw;
        }

        public string SetFilePath(string driveLetter, string folder)
        {
            // Specify a "currently active folder" 
            string activeDir = driveLetter + @":\";

            //Create a new subfolder under the current active folder 
            string newPath = System.IO.Path.Combine(activeDir, folder);

            // Create the subfolder
            System.IO.Directory.CreateDirectory(newPath);

            return newPath;
        }
    }
}

Output:

My first line of text
Second line of text
My third line of text

You can also append like this:

namespace TextFileWriter
{
    public partial class _Default : System.Web.UI.Page
    {       
        //Create your objects here for global scope
        //Create the file
        FileStream theFile;

        //Create the StreamWriter object to do the writing
        StreamWriter sw;

        int x;

        protected void Page_Load(object sender, EventArgs e)
        {
            x = 0;

            for (int i = 0; i < 5; i++)
            {
                function1();
            }
        }

        public void function1()
        {
            x++;

            theFile = new FileStream(@"C:\DEV_LOGS\test.txt", FileMode.Append);

            sw = new StreamWriter(theFile);
            sw.WriteLine(x.ToString() + " line of text");

            sw.Close();
            theFile.Close();
        }
    }
}

Output:
1 line of text
2 line of text
3 line of text
4 line of text
5 line of text

Check this site out for different ways to open a file.

Blog at WordPress.com.