December 2010 - Posts - More Wally - Wallace B. McClure
in

MoreWally.com

Giving people what they want, More Wally. This is the technical and personal blog site of
Wallace B. (Wally) McClure.

This Blog

Syndication

News

Please goy buy 3-4 copies of my book on MonoTouch titled "Professional Android Programming with Mono for Android for .NET/C# Developers." They make great gifts all year round. Plus, I get about $.25 when you buy a copy.

Technical Sites

More Wally - Wallace B. McClure

This blog will have all kinds of posts about Wally McClure. In it, there will be tons of .NET and computer programming posts as well as Wally's views on life in general. As you might guess, this site and blog help you get More Wally in your life. What more could anyone want? iPhone, Android, MonoTouch, MonoDroid, Mobile, HTML5, .NET, ADO.NET, ASP.NET, AJAX, jQuery, jQuery Mobile, ASP.NET AJAX, and Windows Azure............follow me on twitter at Wally

December 2010 - Posts

  • Cool LINQ over JSON..........In MonoDroid no less

    I was working on some json/rest web services written in windows communication foundation (wcf).  I wanted to use the System.Json namespace to do some of this.  I made an http web request asynchronously.  In my call back method, I have following code doing a linq query over this json result.

    System.Json.JsonArray jsonArray = (System.Json.JsonArray)System.Json.JsonArray.Load(strm);
    var twt = (from jsonTweet in jsonArray
                select new Tweet
                {

                    ProfileImage = jsonTweet["ProfileImage"].ToString(),
                    Status = jsonTweet["Status"].ToString(),
                    StatusDate = jsonTweet["StatusDate"],
                    StatusId = Convert.ToInt64(jsonTweet["StatusId"].ToString()),
                    UserName = jsonTweet["UserName"].ToString()
                }).ToList<Tweet>(); 

    Now I have a list of type Tweet. 

    fyi, I didn't need to do a .ToList<> for this, but I was doing something else.

    I hope this helps you out in your coding

  • Wrapping your WCF Responses (or should it be Christmas Presents)

    I've got a WCF web service that exposes its data over REST.  I'm calling it from iPhone and Android.  The method signature is something like:

        [WebInvoke(UriTemplate = "/UserValidate",
        Method = "POST",
        BodyStyle = WebMessageBodyStyle.Wrapped,
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json)]
        public bool UserValidate(string user, string pwd);

    In the response, I've been getting something like this:

    { "UserValidateResult": { true } }

    This is crap as all I wanted is { true } or { false }. You can imagine that when there was a bigger result coming back how this would complicate things.  I just want my basic data, nothing more or less.  How the heck do you get rid of the additional "UserValidateResult" junk.  Well, now we know.  See that BodyStyle attribute on the interface?  Change it to:

    BodyStyle = WebMessageBodyStyle.WrapperRequest

    Now, it seems to pass back what I need, which is { true / false }

    PS.  Hopefully, I didn't mangle this entry as its not been pulled 100% from my project. I can't just copy this code in.

    PSS.  Thanks to my buddy Nathan Blevins for pointing me in the right direction.

  • Writing to the UI with MonoDroid using RunOnUIThread

    I've been pulling my hair out over the past day or so trying to update the UI in my test app.  I was having problem after problem.  I finally got down to my base problem.  I could not write out to my TextView.  WTF could be causing that?  I can write to my UI in other parts of my app.  This is pure craziness.  I thought long and hard and nothing was coming to me.  Wait, the light bulb went on.  I am in the wrong thread.  Great, how do I write in the correct thread?  MonoDroid supports the entire AsyncTask set of objects, but this seemed like overkill.  I was reading and came across RunOnUIThread().......Bing..........The lightbulb has been invented...BlueStar Airlines (oh wait, wrong context). Anyway, here is what I needed:

    this.RunOnUiThread(() => TextViewControl.Text = "Hello World");

    Enjoy!!!!!!!  Remember kiddies, running on the main ui for off device operations is bad, not as bad as crossing the streams bad, but bad as in trying to drive on a flat tire bad. It won't kill you, but it does keep you from getting anywhere.

  • Getting the Dalvik Debug Monitor Service to run on Windows with Android 2.3 SDK

     As I found out, DDMS doesn't run by default when you install the Android 2.3 SDK in Windows.  If you start it up, you get an error message "Failed to get the adb version: Cannot run program "adb": CreateProcess error=2, The system cannot find the file specified."  Thankfully, with the magic of internet search engines, I figured out that I had to add the directory that contains adb to my path statement in Windows7.  After that, it just all worked.ddms

  • Professional Android Programming with MonoDroid and .NET/C#

    Professional Android Programming with MonoDroid and .NET/C# is now listed on Amazon.com and Wiley/Wrox.  Here's a little bit about our book.

    Professional Android Programming with MonoDroid and .NET/C# provides experienced .NET and C# developers with the knowledge the need to become successful Android application developers without having to learn another language. Professional Android Programming with MonoDroid and .NET/C# covers:

    • MonoDroid and MonoDevelop
    • Screen controls, UI development
    • Data controls, windows, and controllers
    • Working with data, REST, SOAP, XML, and JSON
    • Tables and layouts
    • Maps, Geolocation, Geocoding, and MonoDroid
    • Device feature support for networking, battery, accelerometer, orientation, and proximity
    • Multimedia, pictures, video, and audio recording and playback
    • Communicating with other applications
    • Internationalization and Localization
    • Deploying apps, and making money

    I'm excited about working with my fellow coauthors:

    • Nathan Blevins.
    • Jon D.
    • Chris Hardy.
    • John Croft.
    Personally, I view this as a companion book to our existing MonoTouch book (Professional iPhone Programming with MonoTouch and .NET/C#).
  • Calling a REST Based JSON Endpoint with HTTP POST and WCF

    Note: I always forget this stuff, so I'm putting it my blog to help me remember it.

    Calling a JSON REST based service with some params isn't that hard.  I have an endpoint that has this interface:

            [WebInvoke(UriTemplate = "/Login",
                Method="POST",
                BodyStyle = WebMessageBodyStyle.Wrapped,
                RequestFormat = WebMessageFormat.Json,
                ResponseFormat = WebMessageFormat.Json )]
            [OperationContract]
            bool Login(LoginData ld);

    The LoginData class is defined like this:

        [DataContract]
        public class LoginData
        {
            [DataMember]
            public string UserName { get; set; }
            [DataMember]
            public string PassWord { get; set; }
            [DataMember]
            public string AppKey { get; set; }
        }
     

    Now that you see my method to call to login as well as the class that is passed for the login, the body of the login request looks like this:

    { "ld" : {  "UserName":"testuser", "PassWord":"ackkkk", "AppKey":"blah" } }

    The header (in Fiddler), looks like this:

    User-Agent: Fiddler
    Host: hostname
    Content-Length: 76
    Content-Type: application/json

    And finally, my url to POST against is:

    http://www.something.com/...../someservice.svc/Login

    And there you have it, calling a WCF JSON Endpoint thru REST (and HTTP POST)

  • How did I get here? My route to Android, iPhone, Windows Phone 7, and interest in Mobile Devices

    I get asked all the time how/why I got interested in mobile and jumped on this fairly early.  I tend to give half answers because it wasn't just one thing that took me to mobile, but a whole host of separate ivents culminating in a specific event where I wasdoing market research in May/June 2008.  Let me throw out the events and the facts about me:

    • I tend to like new, different, cool stuff.  I jumped on .NET early on.  I jumped on Ajax early on.  I don't jump on every new technology that comes down the road, I'm probably the only person on the planet that doesn't "get" MVC, though I acknowledge that a lot of people do and it solves a number of problems in the default settings of ASP.NET WebForms.
    • I remember buying an early Windows CE device. It was interesting, but dang, this stylus thing sucks. After I lost my third stylus, i just gave up. 
    • I got my first mobile phone in early 1999.  Reception was crappy, but I could see the value in being mobile.
    • In 1999, I worked on a manufacturing systems project.  One piece of the projects was a set of handheld devices on the shop floor.  While the UI was a crappy DOS based, yes I said DOS as in Disk Operating System Version 6.22, I could see that the wireless world was a direction I wanted to be in.
    • In 2000, Microsoft released the first public alpha of .NET.  Very cool stuff indeed.  One piece of the puzzle was a set of mobile controls for ASP.NET.  I build numerous test apps as well as mobile version using these mobile controls.  Now, the mobile UIs of the time were based on WML, which was crap.
    • I could real all the analysis of mobile and read all about growth rates.  Now, you have to realize that growth rates can be impressive when dealing with small numbers, but I knew it was a comer.
    • In our first book, I got talked out of mobile because of the line from the publisher "Wally, mobile doesn't sell."
    • Blackberry was the dominant device of the mid 2000s.  Its users were referred to as "Crackberry addicts."  Unfortunately, the mobile development experience for native apps was crap and the web experience was fairly rough as well, but if they could get the ecosystem started, other phones and better blackberryies would come out.  I finally jumped into using a blackberry.
    • Sometime around 2006, I heard "Wally, mobile doesn't sell" again.  Now, anyone that knows me knows that someone saying something like this to me means I'll keep trying it.
    • The phones of the mid 2000s were moving to be more graphical, but there were too many that had this idea that they had to use a stylus.  Stylus suck.  They get lost too easily.
    • I worked on a project in 2007 and 2008 for a startup trying to answer the question of "What is there to do where I am at?"  For some reason, they wanted to be tied to PCs.  As it became obvious that they were having problems, their investor asked us to do some market research and to figure out what the marketplace did want.  One of the important things that I figured out was the we lived in a mobile world and if you had a mobile app, it need to be on a mobile device, not tied to a desktop/laptop/netbook device. 
    • If there was any single event, this was it - I was doing some market research and sat and talked to people in a bar/restaurant in Atlanta called "The Grove" on Lavista.  The consensus of the people that I talked to was that they wanted their data where ever they were at, laptop, pc, mobile, whereever.
    • In 2007, Apple released the iPhone.  Wow, what an impressive device, even with all the problems of a 1st generation device.  I bought an iPod Touch 1st generation to understand touch better, one of the best decisions I ever made.
    • I decided in late 2008, to make a move into cloud, for a number of reasons.  I was working on an example app.  In April, 2009, one of my friends at Microsoft said "don't mention my name with this, but you need an iPhone front end for this app."  How do you get on the iPhone.  Well, there are a number of ways including:
      • ObjectiveC.  Its hard to teach an old dog new tricks, and this dog knows .NET, not ObjectiveC.
      • HTML, web, javascript optimized interface.  yeah, this is possible.
      • PhoneGap.  Now, this is interesting, take an html interface and get it to run on the iPhone, Android, Blackberry, and other platforms.  I thought that this way made the most sense for me until.........
      • MonoTouch.  In May/June 2009, Novell announced a way for .NET/c# developers to write apps for the iPhone.  This is the way that made the most sense to me.
      • Titanium by Appcelerator.  This is similar in concept to PhoneGap.  I haven't played with this much but do want to learn more about it.
    • In July, 2009, I emailed one of my contacts at Wrox to see if they would be interested in a short MonoTouch ebook in their Wrox Blox format.  I fully expected another  response along the lines of "Wally, mobile doesn't sell."  The response I got was "Wally, iPhone is H O T, get started immediately, can you have this to me before Labor Day."  Not quite the response I expected.  Thankfully, we didn't make the Labor Day, first draft date. I kept pushing back because I had a feeling that things were not going to be quite as polished and feature rich as necessary.  After all, Novell doesn't have the resouces of Microsoft's developer division.
    • The ebook shipped on November 30, 2009.
    • On about December, 15, 2009, my editor emailed and said "Your ebook is selling really well, lets do a full book and it by March 1 so get started."  Thankfully, guys like Craig Dunn and Chris Hardy were interested along with Martin and Ror joinged us later on.
    • I bought my wife an iPhone 3Gs in early 2010 to go along with all my iPod Touch devices.
    • I tried to pretend in 2010 that I wasn't that interested in mobile and still had interest in the desktop technologies.  I love the technologies and continue to use them today, but that isn't where my interest is right now.  I'm just about all mobile all the time with my energies. 
    • Our book shipped in the beginning of July, 2010 right in the middle of the Apple FUD.
    • I've been looking at Mobile Web as a way around the AppStores and Apple FUD problems of 2010.
    • With all the Apple self FUD, we became interested in Android.
    • I went up to Dino Esposito at DevConnections in Las Vegas at introduced myself. I've always tried to keep up with what Dino has been doing. I was shocked, he wanted to meet me.  We must have talked for 1.5 hours. It was way more time than I deserved. If you get a chance, go and introduce yourself to Dino. He's a great guy.
    • Microsoft released Windows Phone 7 in the Fall of 2010.  I'm not doing development on that platform at this time.  I think they have a very interesting user interface.  The devices are being positively reviewed.  For my purposes, the devices are limited at this point in time.  We'll see what 2011 brings as far as updates to the operating system.  I need multitasking/background processing and html5 in the browser. Add that as well as acceptance in the marketplace and I'll be more interested in the device.
    • Obviosuly, I'm now working on a MonoDroid book .
    • I own Android and iPhone/iOS devices.  I am currently working on some startup ideas and am exploring as much in that area as I can.
    • For 2011, I'm planning on speaking at Android Developer's Conference (AnDevCon) and Mobile Connections.  I'm really excited about this.
    • I have a couple of magazine articles coming out in 2011 on Android and iPhone development with the Mono technologies.
    • is Mono "The Answer"? What's "The Question?" I think it will work for me.  It might work for you, it might not.  it depends on your situation.  Its the current horse that I am riding. I might find a better horse tomorrow.

    So, that's how I got here.  I'm in love with mobile.  Mobile native apps on the device as well as mobile web.  I'm into all this cool stuff.  Where are you at?

  • Using Razor, CSHTML, ASP.NET Web Pages, WebMatrix as a web service

    I've been trying to learn about Razor, CSHTML, ASP.NET Web Pages, and WebMatrix.  I've been writing some examples specifically targetting HTML5 mobile apps.  After all, the best way to learn a technology is to dive into it.  I wanted to call some web services in a web page, so of course, I was going to use CSHTML.  I wrote some code that didn't need any parameters, that was pretty easy.  However, what do you do when you want to pass some parameters in.  There are two solutions I can think of:

    • Pass the params in the QueryString, perform a GET operation, and request the items in the CSHTML file.  This is easy, simple, and makes sense.  You code would need to protect the entries that are passed in on the url, but hey, you already know how easy it is to change them.  So, this is what I am doing here.
    • Pass the params in the Body, perform a POST operation, and request the items in the CSHTML file.  This takes a little more work, but I think its a better way to do things. 

    I decided to pass in a GET because I just needed to do something simple and get data.  I like REST principles, but I'm no zealot that things have to be done X way.  Here's my javascript client side code using jQuery and jQuery Mobile:

    function WhereIsUserNow() {
    var UserToView = "@UserToView";
    $.ajax({
    type: "GET",
    url: "@Href("~")Services/MostRecent.cshtml?UserToView=" + UserToView,
    dataType: "json",
    contentType: "application/json",
    success: function (outPut) {
    WhereUserHasBeenMostRecent(outPut);
    },
    error: function (xml, err) {
    alert("err:" + xml.responseText);
    }
    });
    }
    else {
    alert("Please select a user before trying this tab.");
    }
    }

    And now here's my server side cshtml code:

    @{   
       
    string UserName = Membership.GetUser().UserName; 
        string UserToView = Request.Params["UserToView"];
        //do a bunch of things.
        Response.Write(Json.Encode(UserNow));
    }

    Finally, my code will send json data out the client web browser.  Thankfully, it all seems to be working.  Probably need some added security somewhere, but who doesn't. 

    My second point in this is that I'm not saying that Razor/CSHTML is the best place for writing a web service.  I'm sure that there are security holes in this approach that have nothing to do with the technology.  Anyway, here it is, enjoy.

    PS. I had to make a hand edit on this. Hopefully, I didn't muck it up too much.

  • jQuery Templates and jQuery Mobile

    I've been playing with the beta jQuery Templating engine.  I started to play with jQuery Mobile over the weekend.  Basically, I wanted to display information from a web service, put it into a ul/li list and have it display information.  I could call the web service and get data back. Everything was working just fine in that I could get the data back.  Unfortunately, when I bound the data, it just looked like a ul/li list.  I knew I need to do something, but danged if I could figure out what I was doing wrong.  Thankfully, my buddy Dave Ward pointed out what the problem was.  I needed to refresh my listview.  Thanks to Dave, here's the code that I came up with:  The one piece that I was missing was the listview's refresh method.

        <ul id="OptionContainer" data-role="listview" data-theme="a">
           
        </ul>
     
        <script id="userTemplate" type="text/x-jQuery-tmpl">
            <li class="ul-li-icon">
                <a href="">
                <img src="@Href("~")images/users.png" height="30px" />
                ${UserName} ${FirstName} ${MiddleName} ${LastName}
                </a>
            </li>
        </script>
     
        <script language="javascript" type="text/javascript">
            jQuery(function ($) {
                $.ajax({
                    type: "POST",
                    url: "@Href("~")Services/Users.cshtml",
                    dataType: "json",
                    contentType: "application/json",
                    success: function (outPut) {
                        Users(outPut);
                    },
                    error: function (xml, err) {
                        alert(xml.responseText);
                        //for(m in xml)
                        //    alert(m);
                        //alert("err:" + err);
                    }
                });

            });
            function Users(result){
                $("#userTemplate").tmpl(result).appendTo("#OptionContainer");
                $("#OptionContainer").listview("refresh");
            }

     

  • jQuery Mobile Page Transitions

    I've been reading up on jQuery Mobile Page Transitions.  Very cool.  There are currently (alpha 2 level) 6 defined transitions.  These are:

    • slide.
    • slideup.
    • slidedown.
    • pop.
    • fade.
    • flip.

     to use these define your link tags like this:

    <a href="page.aspx" data-transition="slide">slide transition</a>.

    Also, you can force a "backwards" transition by setting the attribute data-back="true".

     

  • My challenges in upgrading my Windows Azure App from SDK 1.2 to 1.3

    I finally got around yesterday evening to updating my Windows Azure Application from the 1.2 SDK to the 1.3 SDK.  Wow, what a fun strange trip that was.  Yes Virginia, it is possible to upgrade.  I ran across the following two issues:

    • Don't try to use beta features if you aren't signed up for them.  Ok, this one should have been obvious, unfortunately, it wasn't.  What was my first thought when I started my upgrade? Of course, it was to try out the ExtraSmall VM.  So, I plugged that into my .csdef file..........and my deployment promptly died with no info as to what had happened beyond some cryptic messages.  Finally, I dug through and figure out that the "Windows.Azure.......PassWord.Encryption.........IDonCareWhatYouTriedToDoException" meant that my app did not have the ExtraSmall VM beta allowed on Azure.  I went back to the Small VM Size to deploy my app with, and the app deployed.  Problem #1 solved.
    • Did I test my app after I deployed it?  Of course not.  Its my test app. There are a few users, but nothing huge.  I logged in this morning, and bomb, the app died.  WTF had I done?  WTF was broken due to moving from 1.2 to 1.3?  I was getting this error

      “SetConfigurationSettingPublisher needs to be called before FromConfigurationSetting can be used”


      I looked at the error, set some break points and ran locally. Boom, it didn't work here either.  Great, what was wrong.  Finally, I found the answer. The change to using the Full IIS7 instead of the Web Core had introduced a breaking change in the app.  So, I copied some code from my WebRole.cs to my Global.asax and things worked.  Sweetness.  Here is the code, it will look a little familiar to someone developing in Azure.
            void Application_Start(object sender, EventArgs e)
            {
                // Code that runs on application startup
                CloudStorageAccount.SetConfigurationSettingPublisher(
                     (configName, configSettingPublisher) =>
                     {
                         var connectionString = RoleEnvironment.IsAvailable
                         ? RoleEnvironment.GetConfigurationSettingValue(configName)
                         : ConfigurationManager.AppSettings[configName];
                         connectionString = RoleEnvironment
                                  .GetConfigurationSettingValue(configName);
                         configSettingPublisher(connectionString);
                     });

                // For information on handling configuration changes
                // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
                RoleEnvironment.Changing += RoleEnvironmentChanging;

            }
            private void RoleEnvironmentChanging(object sender, RoleEnvironmentChangingEventArgs e)
            {
                // If a configuration setting is changing
                if (e.Changes.Any(change => change is RoleEnvironmentConfigurationSettingChange))
                {
                    // Set e.Cancel to true to restart this role instance
                    e.Cancel = true;
                }
            }

    Now, my Azure app is back running and chugging along. Hopefully, this helps you out some.
  • ASP.NET Podcast Show #148 - ASP.NET WebForms to build a Mobile Web Application

    Check the podcast site for the original url.

    This is the video and source code for an ASP.NET WebForms app that I wrote that is optimized for the iPhone and mobile environments. 

    Subscribe to everything.

    Subscribe to WMV.

    Subscribe to M4V for iPhone/iPad.

    Subscribe to MP3.

    Download WMV.

    Download M4V for iPhone/iPad.

    Download MP3.

    Link to iWebKit.

    Source Code:

    <%@ Page Title="MapSplore" Language="C#" MasterPageFile="iPhoneMaster.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="AT_iPhone_Default" %>

    <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="Content" Runat="Server" ClientIDMode="Static">
        <asp:ScriptManager ID="sm" runat="server"
            EnablePartialRendering="true" EnableHistory="false" EnableCdn="true" />
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
        <script  language="javascript"  type="text/javascript">
        <!--
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandle);
        function endRequestHandle(sender, Args) {
            setupMapDiv();
            setupPlaceIveBeen();
        }
        function setupPlaceIveBeen() {
            var mapPlaceIveBeen = document.getElementById('divPlaceIveBeen');
            if (mapPlaceIveBeen != null) {
                var PlaceLat = document.getElementById('<%=hdPlaceIveBeenLatitude.ClientID %>').value;
                var PlaceLon = document.getElementById('<%=hdPlaceIveBeenLongitude.ClientID %>').value;
                var PlaceTitle = document.getElementById('<%=lblPlaceIveBeenName.ClientID %>').innerHTML;
                var latlng = new google.maps.LatLng(PlaceLat, PlaceLon);
                var myOptions = {
                    zoom: 14,
                    center: latlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(mapPlaceIveBeen, myOptions);
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(PlaceLat, PlaceLon),
                    map: map,
                    title: PlaceTitle,
                    clickable: false
                });
            }
        }
        function setupMapDiv() {
            var mapdiv = document.getElementById('divImHere');
            if (mapdiv != null) {
                var PlaceLat = document.getElementById('<%=hdPlaceLat.ClientID %>').value;
                var PlaceLon = document.getElementById('<%=hdPlaceLon.ClientID %>').value;
                var PlaceTitle = document.getElementById('<%=hdPlaceTitle.ClientID %>').value;
                var latlng = new google.maps.LatLng(PlaceLat, PlaceLon);
                var myOptions = {
                    zoom: 14,
                    center: latlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(mapdiv, myOptions);
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(PlaceLat, PlaceLon),
                    map: map,
                    title: PlaceTitle,
                    clickable: false
                });
            }

        }
        -->
        </script>
        <asp:HiddenField ID="Latitude" runat="server" />
        <asp:HiddenField ID="Longitude" runat="server" />
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js%22%3E%3C/script>
        <script language="javascript" type="text/javascript">
            $(document).ready(function () {
                GetLocation();
                setupMapDiv();
                setupPlaceIveBeen();
            });
            function GetLocation() {
                if (navigator.geolocation != null) {
                    navigator.geolocation.getCurrentPosition(getData);
                }
                else {
                    var mess = document.getElementById('<%=Message.ClientID %>');
                    mess.innerHTML = "Sorry, your browser does not support geolocation. " +
                        "Try the latest version of Safari on the iPhone, Android browser, or the latest version of FireFox.";
                }
            }
            function UpdateLocation_Click() {
                GetLocation();
            }
            function getData(position) {
                var latitude = position.coords.latitude;
                var longitude = position.coords.longitude;
                var hdLat = document.getElementById('<%=Latitude.ClientID %>');
                var hdLon = document.getElementById('<%=Longitude.ClientID %>');
                hdLat.value = latitude;
                hdLon.value = longitude;
            }
        </script>
        <asp:Label ID="Message" runat="server" />
        <asp:UpdatePanel ID="upl" runat="server">
            <ContentTemplate>
        <asp:Panel ID="pnlStart" runat="server" Visible="true">
        <div id="topbar">
            <div id="title">MapSplore</div>
        </div>
        <div id="content">
            <ul class="pageitem">
                <li class="menu">
                    <asp:LinkButton ID="lbLocalDeals" runat="server" onclick="lbLocalDeals_Click">
                    <asp:Image ID="imLocalDeals" runat="server" ImageUrl="~/Images/ArtFavor_Money_Bag_Icon.png" Height="30" />
                    <span class="name">Local Deals.</span>
                    <span class="arrow"></span>
                    </asp:LinkButton>
                    </li>
                <li class="menu">
                    <asp:LinkButton ID="lbLocalPlaces" runat="server" onclick="lbLocalPlaces_Click">
                    <asp:Image ID="imLocalPlaces" runat="server" ImageUrl="~/Images/Andy_Houses_on_the_horizon_-_Starburst_remix.png" Height="30" />
                    <span class="name">Local Places.</span>
                    <span class="arrow"></span>
                    </asp:LinkButton>
                    </li>
                <li class="menu">
                    <asp:LinkButton ID="lbWhereIveBeen" runat="server" onclick="lbWhereIveBeen_Click">
                    <asp:Image ID="imImHere" runat="server" ImageUrl="~/Images/ryanlerch_flagpole.png" Height="30" />
                    <span class="name">I've been here.</span>
                    <span class="arrow"></span>
                    </asp:LinkButton>
                    </li>
                <li class="menu">
                    <asp:LinkButton ID="lbMyStats" runat="server">
                    <asp:Image ID="imMyStats" runat="server" ImageUrl="~/Images/Anonymous_Spreadsheet.png" Height="30" />
                    <span class="name">My Stats.</span>
                    <span class="arrow"></span>
                    </asp:LinkButton>
                    </li>
                <li class="menu">
                    <asp:LinkButton ID="lbAddAPlace" runat="server" onclick="lbAddAPlace_Click">
                    <asp:Image ID="imAddAPlace" runat="server" ImageUrl="~/Images/jean_victor_balin_add.png" Height="30" />
                    <span class="name">Add a Place.</span>
                    <span class="arrow"></span>
                    </asp:LinkButton>
                    </li>
                <li class="button">
                    <input type="button" value="Update Your Current Location" onclick="UpdateLocation_Click()">
                    </li>
            </ul>
        </div>
        </asp:Panel>
        <div>
        <asp:Panel ID="pnlCoupons" runat="server" Visible="false">
            <div id="topbar">
            <div id="title">MapSplore</div>
            <div id="leftbutton">
                <asp:LinkButton runat="server" Text="Return"
                    ID="ReturnFromDeals" OnClick="ReturnFromDeals_Click" /></div></div>
        <div class="content">
        <asp:ListView ID="lvCoupons" runat="server">
            <LayoutTemplate>
                <ul class="pageitem" runat="server">
                    <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
                </ul>
            </LayoutTemplate>
            <ItemTemplate>
                <li class="menu">
                    <asp:LinkButton ID="lbBusiness" runat="server" Text='<%#Eval("Place.Name") %>' OnClick="lbBusiness_Click">
                        <span class="comment">
                        <asp:Label ID="lblAddress" runat="server" Text='<%#Eval("Place.Address1") %>' />
                        <asp:Label ID="lblDis" runat="server" Text='<%# Convert.ToString(Convert.ToInt32(Eval("Place.Distance"))) + " meters" %>' CssClass="smallText" />
                        <asp:HiddenField ID="hdPlaceId" runat="server" Value='<%#Eval("PlaceId") %>' />
                        <asp:HiddenField ID="hdGeoPromotionId" runat="server" Value='<%#Eval("GeoPromotionId") %>' />
                        </span>
                        <span class="arrow"></span>
                    </asp:LinkButton></li></ItemTemplate></asp:ListView><asp:GridView ID="gvCoupons" runat="server" AutoGenerateColumns="false">
                <HeaderStyle BackColor="Silver" />
                <AlternatingRowStyle BackColor="Wheat" />
                <Columns>
                    <asp:TemplateField AccessibleHeaderText="Business" HeaderText="Business">
                        <ItemTemplate>
                            <asp:Image ID="imPlaceType" runat="server" Text='<%#Eval("Type") %>' ImageUrl='<%#Eval("Image") %>' />
                            <asp:LinkButton ID="lbBusiness" runat="server" Text='<%#Eval("Name") %>' OnClick="lbBusiness_Click" />
                            <asp:LinkButton ID="lblAddress" runat="server" Text='<%#Eval("Address1") %>' CssClass="smallText" />
                            <asp:Label ID="lblDis" runat="server" Text='<%# Convert.ToString(Convert.ToInt32(Eval("Distance"))) + " meters" %>' CssClass="smallText" />
                            <asp:HiddenField ID="hdPlaceId" runat="server" Value='<%#Eval("PlaceId") %>' />
                            <asp:HiddenField ID="hdGeoPromotionId" runat="server" Value='<%#Eval("GeoPromotionId") %>' />
                            <asp:Label ID="lblInfo" runat="server" Visible="false" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </div>
        </asp:Panel>
        <asp:Panel ID="pnlPlaces" runat="server" Visible="false">
        <div id="topbar">
            <div id="title">
                MapSplore</div><div id="leftbutton">
                <asp:LinkButton runat="server" Text="Return"
                    ID="ReturnFromPlaces" OnClick="ReturnFromPlaces_Click" /></div></div>
            <div id="content">
            <asp:ListView ID="lvPlaces" runat="server">
                <LayoutTemplate>
                    <ul id="ulPlaces" class="pageitem" runat="server">
                        <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
                        <li class="menu">
                            <asp:LinkButton ID="lbNotListed" runat="server" CssClass="name"
                                OnClick="lbNotListed_Click">
                                Place not listed
                                <span class="arrow"></span>   
                            </asp:LinkButton>
                        </li>
                    </ul>
                </LayoutTemplate>
                <ItemTemplate>
                <li class="menu">
                    <asp:LinkButton ID="lbImHere" runat="server" CssClass="name"
                        OnClick="lbImHere_Click">
                    <%#DisplayName(Eval("Name")) %>&nbsp;
                    <%# Convert.ToString(Convert.ToInt32(Eval("Distance"))) + " meters" %>
                    <asp:HiddenField ID="hdPlaceId" runat="server" Value='<%#Eval("PlaceId") %>' />
                    <span class="arrow"></span>
                    </asp:LinkButton></li></ItemTemplate></asp:ListView>
        </div>
        </asp:Panel>
        <asp:Panel ID="pnlImHereNow" runat="server" Visible="false">
            <div id="topbar">
            <div id="title">
                MapSplore</div><div id="leftbutton">
                <asp:LinkButton runat="server" Text="Places"
                    ID="lbImHereNowReturn" OnClick="lbImHereNowReturn_Click" /></div></div>
                <div id="rightbutton">
                <asp:LinkButton runat="server" Text="Beginning"
                    ID="lbBackToBeginning" OnClick="lbBackToBeginning_Click" />
                </div>
            <div id="content">
            <ul class="pageitem">
            <asp:HiddenField ID="hdPlaceId" runat="server" />
            <asp:HiddenField ID="hdPlaceLat" runat="server" />
            <asp:HiddenField ID="hdPlaceLon" runat="server" />
            <asp:HiddenField ID="hdPlaceTitle" runat="server" />
            <asp:Button ID="btnImHereNow" runat="server"
                Text="I'm here" OnClick="btnImHereNow_Click" />
                <asp:Label ID="lblPlaceTitle" runat="server" /><br />
            <asp:TextBox ID="txtWhatsHappening" runat="server" TextMode="MultiLine" Rows="2" style="width:300px" /><br />
            <div id="divImHere" style="width:300px; height:300px"></div>
            </div>
            </ul>
        </asp:Panel>
        <asp:Panel runat="server" ID="pnlIveBeenHere" Visible="false">
            <div id="topbar">
            <div id="title">
                Where I've been</div><div id="leftbutton">
                <asp:LinkButton ID="lbIveBeenHereBack" runat="server" Text="Back" OnClick="lbIveBeenHereBack_Click" /></div></div>
            <div id="content">
            <asp:ListView ID="lvWhereIveBeen" runat="server">
                <LayoutTemplate>
                    <ul id="ulWhereIveBeen" class="pageitem" runat="server">
                        <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
                    </ul>
                </LayoutTemplate>
                <ItemTemplate>
                <li class="menu" runat="server">
                    <asp:LinkButton ID="lbPlaceIveBeen" runat="server" OnClick="lbPlaceIveBeen_Click" CssClass="name">
                        <asp:Label ID="lblPlace" runat="server" Text='<%#Eval("PlaceName") %>' /> at
                        <asp:Label ID="lblTime" runat="server" Text='<%#Eval("ATTime") %>' CssClass="content" />
                        <asp:HiddenField ID="hdATID" runat="server" Value='<%#Eval("ATID") %>' />
                        <span class="arrow"></span>
                    </asp:LinkButton>
                </li>
                </ItemTemplate>
            </asp:ListView>
            </div>
            </asp:Panel>
        <asp:Panel runat="server" ID="pnlPlaceIveBeen" Visible="false">
            <div id="topbar">
            <div id="title">
                I've been here
            </div>
            <div id="leftbutton">
                <asp:LinkButton ID="lbPlaceIveBeenBack" runat="server" Text="Back" OnClick="lbPlaceIveBeenBack_Click" />
            </div>
            <div id="rightbutton">
                <asp:LinkButton ID="lbPlaceIveBeenBeginning" runat="server" Text="Beginning" OnClick="lbPlaceIveBeenBeginning_Click" />
            </div>
            </div>
            <div id="content">
                <ul class="pageitem">
                <li>
                <asp:HiddenField ID="hdPlaceIveBeenPlaceId" runat="server" />
                <asp:HiddenField ID="hdPlaceIveBeenLatitude" runat="server" />
                <asp:HiddenField ID="hdPlaceIveBeenLongitude" runat="server" />
                <asp:Label ID="lblPlaceIveBeenName" runat="server" /><br />
                <asp:Label ID="lblPlaceIveBeenAddress" runat="server" /><br />
                <asp:Label ID="lblPlaceIveBeenCity" runat="server" />,
                <asp:Label ID="lblPlaceIveBeenState" runat="server" />
                <asp:Label ID="lblPlaceIveBeenZipCode" runat="server" /><br />
                <asp:Label ID="lblPlaceIveBeenCountry" runat="server" /><br />
                <div id="divPlaceIveBeen" style="width:300px; height:300px"></div>
                </li>
                </ul>
            </div>
               
        </asp:Panel>

            <asp:Panel ID="pnlAddPlace" runat="server" Visible="false">
                    <div id="topbar">
    <div id="title">MapSplore</div><div id="leftbutton">
    <asp:LinkButton ID="lbAddPlaceReturn" runat="server" Text="Back" OnClick="lbAddPlaceReturn_Click" /></div><div id="rightnav">
    </div>
    </div>
    <div id="content">
        <ul class="pageitem">
            <li id="liPlaceAddMessage" runat="server" visible="false">
            <asp:Label ID="PlaceAddMessage" runat="server" />
            </li>
            <li class="bigfield">
            <asp:TextBox ID="txtPlaceName" runat="server" placeholder="Name of Establishment" />
            </li>
            <li class="bigfield">
            <asp:TextBox ID="txtAddress1" runat="server" placeholder="Address 1" />
            </li>
            <li class="bigfield">
            <asp:TextBox ID="txtCity" runat="server" placeholder="City" />
            </li>
            <li class="select">
            <asp:DropDownList ID="ddlProvince" runat="server" placeholder="Select State" /> 
            <span class="arrow"></span>     
            </li>
            <li class="bigfield">
            <asp:TextBox ID="txtZipCode" runat="server" placeholder="Zip Code" />
            </li>
            <li class="select">
            <asp:DropDownList ID="ddlCountry" runat="server"
                onselectedindexchanged="ddlCountry_SelectedIndexChanged" />
            <span class="arrow"></span>
            </li>
            <li class="bigfield">
            <asp:TextBox ID="txtPhoneNumber" runat="server" placeholder="Phone Number" />
            </li>
            <li class="checkbox">
                <span class="name">You Here Now:</span> <asp:CheckBox ID="cbYouHereNow" runat="server" Checked="true" />
            </li>
            <li class="button">
            <asp:Button ID="btnAdd" runat="server" Text="Add Place"
                onclick="btnAdd_Click" />
            </li>
        </ul>
    </div>
            </asp:Panel>
            <asp:Panel ID="pnlImHere" runat="server" Visible="false">
                <asp:TextBox ID="txtImHere" runat="server"
                    TextMode="MultiLine" Rows="3" Columns="40" /><br />
                <asp:DropDownList ID="ddlPlace" runat="server" /><br />
                <asp:Button ID="btnHere" runat="server" Text="Tell Everyone I'm Here"
                    onclick="btnHere_Click" /><br />
            </asp:Panel>

        </div>
        </ContentTemplate>
        </asp:UpdatePanel>

    </asp:Content>

    Code Behind .cs file:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using LocationDataModel;

    public partial class AT_iPhone_Default : ViewStatePage
    {
        private iPhoneDevice ipd;

        protected void Page_Load(object sender, EventArgs e)
        {
            LocationDataEntities lde = new LocationDataEntities();
            if (!Page.IsPostBack)
            {
                var Countries = from c in lde.Countries select c;
                foreach (Country co in Countries)
                {
                    ddlCountry.Items.Add(new ListItem(co.Name, co.CountryId.ToString()));
                }
                ddlCountry_SelectedIndexChanged(ddlCountry, null);
                if (AppleIPhone.IsIPad())
                    ipd = iPhoneDevice.iPad;
                if (AppleIPhone.IsIPhone())
                    ipd = iPhoneDevice.iPhone;
                if (AppleIPhone.IsIPodTouch())
                    ipd = iPhoneDevice.iPodTouch;
            }
        }
        protected void btnPlaces_Click(object sender, EventArgs e)
        {
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            bool blImHere = cbYouHereNow.Checked;
            string Place = txtPlaceName.Text,
                Address1 = txtAddress1.Text,
                City = txtCity.Text,
                ZipCode = txtZipCode.Text,
                PhoneNumber = txtPhoneNumber.Text,
                ProvinceId = ddlProvince.SelectedItem.Value,
                CountryId = ddlCountry.SelectedItem.Value;
            int iProvinceId, iCountryId;
            double dLatitude, dLongitude;
            DataAccess da = new DataAccess();
            if ((!String.IsNullOrEmpty(ProvinceId)) &&
                (!String.IsNullOrEmpty(CountryId)))
            {
                iProvinceId = Convert.ToInt32(ProvinceId);
                iCountryId = Convert.ToInt32(CountryId);
                if (blImHere)
                {
                    dLatitude = Convert.ToDouble(Latitude.Value);
                    dLongitude = Convert.ToDouble(Longitude.Value);
                    da.StorePlace(Place, Address1, String.Empty, City,
                        iProvinceId, ZipCode, iCountryId, PhoneNumber,
                        dLatitude, dLongitude);
                }
                else
                {
                    da.StorePlace(Place, Address1, String.Empty, City,
                        iProvinceId, ZipCode, iCountryId, PhoneNumber);
                }
                liPlaceAddMessage.Visible = true;
                PlaceAddMessage.Text = "Awesome, your place has been added. Add Another!";
                txtPlaceName.Text = String.Empty;
                txtAddress1.Text = String.Empty;
                txtCity.Text = String.Empty;
                ddlProvince.SelectedIndex = -1;
                txtZipCode.Text = String.Empty;
                txtPhoneNumber.Text = String.Empty;
            }
            else
            {
                liPlaceAddMessage.Visible = true;
                PlaceAddMessage.Text = "Please select a State and a Country.";
            }
        }
        protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
            string CountryId = ddlCountry.SelectedItem.Value;
            if (!String.IsNullOrEmpty(CountryId))
            {
                int iCountryId = Convert.ToInt32(CountryId);
                LocationDataModel.LocationDataEntities lde = new LocationDataModel.LocationDataEntities();
                var prov = from p in lde.Provinces where p.CountryId == iCountryId
                           orderby p.ProvinceName select p;
               
                ddlProvince.Items.Add(String.Empty);
                foreach (Province pr in prov)
                {
                    ddlProvince.Items.Add(new ListItem(pr.ProvinceName, pr.ProvinceId.ToString()));
                }
            }
            else
            {
                ddlProvince.Items.Clear();
            }
        }
        protected void btnImHere_Click(object sender, EventArgs e)
        {
            int i = 0;
            DataAccess da = new DataAccess();
            double Lat = Convert.ToDouble(Latitude.Value),
                Lon = Convert.ToDouble(Longitude.Value);
            List<Place> lp = da.NearByLocations(Lat, Lon);
            foreach (Place p in lp)
            {
                ListItem li = new ListItem(p.Name, p.PlaceId.ToString());
                if (i == 0)
                {
                    li.Selected = true;
                }
                ddlPlace.Items.Add(li);
                i++;
            }
            pnlAddPlace.Visible = false;
            pnlImHere.Visible = true;
        }
        protected void lbImHere_Click(object sender, EventArgs e)
        {
            string UserName = Membership.GetUser().UserName;
            ListViewItem lvi = (ListViewItem)(((LinkButton)sender).Parent);
            HiddenField hd = (HiddenField)lvi.FindControl("hdPlaceId");
            long PlaceId = Convert.ToInt64(hd.Value);
            double dLatitude = Convert.ToDouble(Latitude.Value);
            double dLongitude = Convert.ToDouble(Longitude.Value);
            DataAccess da = new DataAccess();
            Place pl = da.GetPlace(PlaceId);
            pnlImHereNow.Visible = true;
            pnlPlaces.Visible = false;
            hdPlaceId.Value = PlaceId.ToString();
            hdPlaceLat.Value = pl.Latitude.ToString();
            hdPlaceLon.Value = pl.Longitude.ToString();
            hdPlaceTitle.Value = pl.Name;
            lblPlaceTitle.Text = pl.Name;
        }
        protected void btnHere_Click(object sender, EventArgs e)
        {
            string UserName = Membership.GetUser().UserName;
            string WhatsH = txtImHere.Text;
            long PlaceId = Convert.ToInt64(ddlPlace.SelectedValue);
            double dLatitude = Convert.ToDouble(Latitude.Value);
            double dLongitude = Convert.ToDouble(Longitude.Value);
            DataAccess da = new DataAccess();
            da.StoreUserAT(UserName, PlaceId, WhatsH,
                dLatitude, dLongitude);
        }
        protected void btnLocalCoupons_Click(object sender, EventArgs e)
        {
            double dLatitude = Convert.ToDouble(Latitude.Value);
            double dLongitude = Convert.ToDouble(Longitude.Value);
            DataAccess da = new DataAccess();

        }
        protected void lbBusiness_Click(object sender, EventArgs e)
        {
            string UserName = Membership.GetUser().UserName;
            GridViewRow gvr = (GridViewRow)(((LinkButton)sender).Parent.Parent);
            HiddenField hd = (HiddenField)gvr.FindControl("hdPlaceId");
            string sPlaceId = hd.Value;
            Int64 PlaceId;
            if (!String.IsNullOrEmpty(sPlaceId))
            {
                PlaceId = Convert.ToInt64(sPlaceId);
            }
        }
        protected void lbLocalDeals_Click(object sender, EventArgs e)
        {
            double dLatitude = Convert.ToDouble(Latitude.Value);
            double dLongitude = Convert.ToDouble(Longitude.Value);
            DataAccess da = new DataAccess();
            pnlCoupons.Visible = true;
            pnlStart.Visible = false;
            List<GeoPromotion> lgp = da.NearByDeals(dLatitude, dLongitude);
            lvCoupons.DataSource = lgp;
            lvCoupons.DataBind();
        }
        protected void lbLocalPlaces_Click(object sender, EventArgs e)
        {
            DataAccess da = new DataAccess();
            double Lat = Convert.ToDouble(Latitude.Value);
            double Lon = Convert.ToDouble(Longitude.Value);
            List<LocationDataModel.Place> places = da.NearByLocations(Lat, Lon);
            lvPlaces.DataSource = places;
            lvPlaces.SelectedIndex = -1;
            lvPlaces.DataBind();
            pnlPlaces.Visible = true;
            pnlStart.Visible = false;
        }
        protected void ReturnFromPlaces_Click(object sender, EventArgs e)
        {
            pnlPlaces.Visible = false;
            pnlStart.Visible = true;
        }
        protected void ReturnFromDeals_Click(object sender, EventArgs e)
        {
            pnlCoupons.Visible = false;
            pnlStart.Visible = true;
        }
        protected void btnImHereNow_Click(object sender, EventArgs e)
        {
            long PlaceId = Convert.ToInt32(hdPlaceId.Value);
            string UserName = Membership.GetUser().UserName;
            string WhatsHappening = txtWhatsHappening.Text;
            double UserLat = Convert.ToDouble(Latitude.Value);
            double UserLon = Convert.ToDouble(Longitude.Value);
            DataAccess da = new DataAccess();
            da.StoreUserAT(UserName, PlaceId, WhatsHappening,
                UserLat, UserLon);
        }
        protected void lbImHereNowReturn_Click(object sender, EventArgs e)
        {
            pnlImHereNow.Visible = false;
            pnlPlaces.Visible = true;
        }
        protected void lbBackToBeginning_Click(object sender, EventArgs e)
        {
            pnlStart.Visible = true;
            pnlImHereNow.Visible = false;
        }
        protected void lbWhereIveBeen_Click(object sender, EventArgs e)
        {
            string UserName = Membership.GetUser().UserName;
            pnlStart.Visible = false;
            pnlIveBeenHere.Visible = true;
            DataAccess da = new DataAccess();
            lvWhereIveBeen.DataSource = da.UserATs(UserName, 0, 15);
            lvWhereIveBeen.DataBind();
        }
        protected void lbIveBeenHereBack_Click(object sender, EventArgs e)
        {
            pnlIveBeenHere.Visible = false;
            pnlStart.Visible = true;
        }

        protected void lbPlaceIveBeen_Click(object sender, EventArgs e)
        {
            LinkButton lb = (LinkButton)sender;
            ListViewItem lvi = (ListViewItem)lb.Parent.Parent;
            HiddenField hdATID = (HiddenField)lvi.FindControl("hdATID");
            Int64 ATID = Convert.ToInt64(hdATID.Value);
            DataAccess da = new DataAccess();
            pnlIveBeenHere.Visible = false;
            pnlPlaceIveBeen.Visible = true;
            var plac = da.GetPlaceViaATID(ATID);
            hdPlaceIveBeenPlaceId.Value = plac.PlaceId.ToString();
            hdPlaceIveBeenLatitude.Value = plac.Latitude.ToString();
            hdPlaceIveBeenLongitude.Value = plac.Longitude.ToString();
            lblPlaceIveBeenName.Text = plac.Name;
            lblPlaceIveBeenAddress.Text = plac.Address1;
            lblPlaceIveBeenCity.Text = plac.City;
            lblPlaceIveBeenState.Text = plac.Province.ProvinceName;
            lblPlaceIveBeenZipCode.Text = plac.ZipCode;
            lblPlaceIveBeenCountry.Text = plac.Country.Name;
        }

        protected void lbNotListed_Click(object sender, EventArgs e)
        {
            SetupAddPoint();
            pnlPlaces.Visible = false;
        }

        protected void lbAddAPlace_Click(object sender, EventArgs e)
        {
            SetupAddPoint();
        }

        private void SetupAddPoint()
        {
            double lat = Convert.ToDouble(Latitude.Value);
            double lon = Convert.ToDouble(Longitude.Value);
            DataAccess da = new DataAccess();
            var zip = da.WhereAmIAt(lat, lon);
            if (zip.Count > 0)
            {
                var z0 = zip[0];
                txtCity.Text = z0.City;
                txtZipCode.Text = z0.ZipCode;
                ddlProvince.ClearSelection();
                if (z0.ProvinceId.HasValue == true)
                {
                    foreach (ListItem li in ddlProvince.Items)
                    {
                        if (li.Value == z0.ProvinceId.Value.ToString())
                        {
                            li.Selected = true;
                            break;
                        }
                    }
                }
            }
            pnlAddPlace.Visible = true;
            pnlStart.Visible = false;
        }
        protected void lbAddPlaceReturn_Click(object sender, EventArgs e)
        {
            pnlAddPlace.Visible = false;
            pnlStart.Visible = true;
            liPlaceAddMessage.Visible = false;
            PlaceAddMessage.Text = String.Empty;
        }
        protected void lbPlaceIveBeenBack_Click(object sender, EventArgs e)
        {
            pnlIveBeenHere.Visible = true;
            pnlPlaceIveBeen.Visible = false;
           
        }
        protected void lbPlaceIveBeenBeginning_Click(object sender, EventArgs e)
        {
            pnlPlaceIveBeen.Visible = false;
            pnlStart.Visible = true;
        }
        protected string DisplayName(object val)
        {
            string strVal = Convert.ToString(val);

            if (AppleIPhone.IsIPad())
            {
                ipd = iPhoneDevice.iPad;
            }
            if (AppleIPhone.IsIPhone())
            {
                ipd = iPhoneDevice.iPhone;
            }
            if (AppleIPhone.IsIPodTouch())
            {
                ipd = iPhoneDevice.iPodTouch;
            }
            return (iPhoneHelper.DisplayContentOnMenu(strVal, ipd));
        }
    }

    iPhoneHelper.cs file:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    public enum iPhoneDevice
    {
        iPhone, iPodTouch, iPad
    }
    /// <summary>
    /// Summary description for iPhoneHelper
    /// </summary>
    ///
    public class iPhoneHelper
    {
     public iPhoneHelper()
     {
      //
      // TODO: Add constructor logic here
      //
     }

    // This code is stupid in retrospect. Use css to solve this problem 

        public static string DisplayContentOnMenu(string val, iPhoneDevice ipd)
        {
            string Return = val;
            string Elipsis = "...";
            int iPadMaxLength = 30;
            int iPhoneMaxLength = 15;
            if (ipd == iPhoneDevice.iPad)
            {
                if (Return.Length > iPadMaxLength)
                {
                    Return = Return.Substring(0, iPadMaxLength - Elipsis.Length) + Elipsis;
                }
            }
            else
            {
                if (Return.Length > iPhoneMaxLength)
                {
                    Return = Return.Substring(0, iPhoneMaxLength - Elipsis.Length) + Elipsis;
                }
            }
            return (Return);
        }

    Source code for the ViewStatePage:

    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;

    /// <summary>
    /// Summary description for BasePage
    /// </summary>
    #region Base class for a page.
    public class ViewStatePage : System.Web.UI.Page
    {

        PageStatePersisterToDatabase myPageStatePersister;
       
        public ViewStatePage()
            : base()
        {
            myPageStatePersister = new PageStatePersisterToDatabase(this);
        }

        protected override PageStatePersister PageStatePersister
        {
            get
            {
                return myPageStatePersister;
            }
        }

    }
    #endregion

    #region This class will override the page persistence to store page state in a database.
    public class PageStatePersisterToDatabase : PageStatePersister
    {
        private string ViewStateKeyField = "__VIEWSTATE_KEY";
        private string _exNoConnectionStringFound = "No Database Configuration information is in the web.config.";

        public PageStatePersisterToDatabase(Page page)
            : base(page)
        {
        }

        public override void Load()
        {

            // Get the cache key from the web form data
            System.Int64 key = Convert.ToInt64(Page.Request.Params[ViewStateKeyField]);

            Pair state = this.LoadState(key);

            // Abort if cache object is not of type Pair
            if (state == null)
                throw new ApplicationException("Missing valid " + ViewStateKeyField);

            // Set view state and control state
            ViewState = state.First;
            ControlState = state.Second;
        }

        public override void Save()
        {

            // No processing needed if no states available
            if (ViewState == null && ControlState != null)
                return;

            System.Int64 key;
            IStateFormatter formatter = this.StateFormatter;
            Pair statePair = new Pair(ViewState, ControlState);

            // Serialize the statePair object to a string.
            string serializedState = formatter.Serialize(statePair);

            // Save the ViewState and get a unique identifier back.
            key = SaveState(serializedState);

            // Register hidden field to store cache key in
            // Page.ClientScript does not work properly with Atlas.
            //Page.ClientScript.RegisterHiddenField(ViewStateKeyField, key.ToString());
            ScriptManager.RegisterHiddenField(this.Page, ViewStateKeyField, key.ToString());
        }

        private System.Int64 SaveState(string PageState)
        {
            System.Int64 i64Key = 0;
            string strConn = String.Empty,
                strProvider = String.Empty;

            string strSql = "insert into tblPageState ( SerializedState ) values ( '" + SqlEscape(PageState) + "');select scope_identity();";
            SqlConnection sqlCn;
            SqlCommand sqlCm;
            try
            {
                GetDBConnectionString(ref strConn, ref strProvider);
                sqlCn = new SqlConnection(strConn);
                sqlCm = new SqlCommand(strSql, sqlCn);
                sqlCn.Open();
                i64Key = Convert.ToInt64(sqlCm.ExecuteScalar());
                if (sqlCn.State != ConnectionState.Closed)
                {
                    sqlCn.Close();
                }
                sqlCn.Dispose();
                sqlCm.Dispose();
            }
            finally
            {
                sqlCn = null;
                sqlCm = null;
            }
            return i64Key;
        }

        private Pair LoadState(System.Int64 iKey)
        {
            string strConn = String.Empty,
                strProvider = String.Empty,
                SerializedState = String.Empty,
                strMinutesInPast = GetMinutesInPastToDelete();
            Pair PageState;
            string strSql = "select SerializedState from tblPageState where tblPageStateID=" + iKey.ToString() + ";" +
                "delete from tblPageState where DateUpdated<DateAdd(mi, " + strMinutesInPast + ", getdate());";
            SqlConnection sqlCn;
            SqlCommand sqlCm;
            try
            {
                GetDBConnectionString(ref strConn, ref strProvider);
                sqlCn = new SqlConnection(strConn);
                sqlCm = new SqlCommand(strSql, sqlCn);

                sqlCn.Open();
                SerializedState = Convert.ToString(sqlCm.ExecuteScalar());
                IStateFormatter formatter = this.StateFormatter;

                if ((null == SerializedState) ||
                    (String.Empty == SerializedState))
                {
                    throw (new ApplicationException("No ViewState records were returned."));
                }

                // Deserilize returns the Pair object that is serialized in
                // the Save method.
                PageState = (Pair)formatter.Deserialize(SerializedState);

                if (sqlCn.State != ConnectionState.Closed)
                {
                    sqlCn.Close();
                }
                sqlCn.Dispose();
                sqlCm.Dispose();
            }
            finally
            {
                sqlCn = null;
                sqlCm = null;
            }
            return PageState;
        }

        private string SqlEscape(string Val)
        {
            string ReturnVal = String.Empty;
            if (null != Val)
            {
                ReturnVal = Val.Replace("'", "''");
            }
            return (ReturnVal);
        }
        private void GetDBConnectionString(ref string ConnectionStringValue, ref string ProviderNameValue)
        {
            if (System.Configuration.ConfigurationManager.ConnectionStrings.Count > 0)
            {
                ConnectionStringValue = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
                ProviderNameValue = System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ProviderName;
            }
            else
            {
                throw new ConfigurationErrorsException(_exNoConnectionStringFound);
            }
        }
        private string GetMinutesInPastToDelete()
        {
            string strReturn = "-60";
            if (null != System.Configuration.ConfigurationManager.AppSettings["MinutesInPastToDeletePageState"])
            {
                strReturn = System.Configuration.ConfigurationManager.AppSettings["MinutesInPastToDeletePageState"].ToString();
            }
            return (strReturn);
        }
    }
    #endregion

    AppleiPhone.cs file:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;

    /// <summary>
    /// Summary description for AppleIPhone
    /// </summary>
    public class AppleIPhone
    {
     public AppleIPhone()
     {
      //
      // TODO: Add constructor logic here
      //
     }

        static public bool IsIPhoneOS()
        {
            return (IsIPad() || IsIPhone() || IsIPodTouch());
        }

        static public bool IsIPhone()
        {
            return IsTest("iPhone");
        }

        static public bool IsIPodTouch()
        {
            return IsTest("iPod");
        }

        static public bool IsIPad()
        {
            return IsTest("iPad");
        }

        static private bool IsTest(string Agent)
        {
            bool bl = false;
            string ua = HttpContext.Current.Request.UserAgent.ToLower();
            try
            {
                bl = ua.Contains(Agent.ToLower());
            }
            catch { }
            return (bl);
       
        }
    }

    Master page .cs:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;

    public partial class MasterPages_iPhoneMaster : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
                HtmlHead head = Page.Header;
                HtmlMeta meta = new HtmlMeta();
                if (AppleIPhone.IsIPad() == true)
                {
                    meta.Content = "width=400,user-scalable=no";
                    head.Controls.Add(meta);
                }
                else
                {
                    meta.Content = "width=device-width, user-scalable=no";
                    meta.Attributes.Add("name", "viewport");
                }
                meta.Attributes.Add("name", "viewport");
                head.Controls.Add(meta);
                HtmlLink cssLink = new HtmlLink();
                HtmlGenericControl script = new HtmlGenericControl("script");
                script.Attributes.Add("type", "text/javascript");
                script.Attributes.Add("src", ResolveUrl("~/Scripts/iWebKit/javascript/functions.js"));
                head.Controls.Add(script);
                cssLink.Attributes.Add("rel", "stylesheet");
                cssLink.Attributes.Add("href", ResolveUrl("~/Scripts/iWebKit/css/style.css") );
                cssLink.Attributes.Add("type", "text/css");
                head.Controls.Add(cssLink);
                HtmlGenericControl jsLink = new HtmlGenericControl("script");
                //jsLink.Attributes.Add("type", "text/javascript");
                //jsLink.Attributes.Add("src", ResolveUrl("~/Scripts/jquery-1.4.1.min.js") );
                //head.Controls.Add(jsLink);
                HtmlLink appleIcon = new HtmlLink();
                appleIcon.Attributes.Add("rel", "apple-touch-icon");
                appleIcon.Attributes.Add("href", ResolveUrl("~/apple-touch-icon.png"));
                HtmlMeta appleMobileWebAppStatusBarStyle = new HtmlMeta();
                appleMobileWebAppStatusBarStyle.Attributes.Add("name", "apple-mobile-web-app-status-bar-style");
                appleMobileWebAppStatusBarStyle.Attributes.Add("content", "black");
                head.Controls.Add(appleMobileWebAppStatusBarStyle);
        }

        internal string FindPath(string Location)
        {
            string Url = Server.MapPath(Location);
            return (Url);
        }
    }

  • Android Developer Conference (AnDevCon) - San Francisco, CA - March, 2011

    I am honored to be presenting at AnDevCon in San Francisco, CA March 7 - 9.  I'll be presenting on MonoDroid, the .NET/C# callable layer for .NET developers to target Android.

    Here is some info on the conference:

    "AnDevCon is the technical conference for software developers building or selling Android apps. Whether you’re an enterprise developer, work for a commercial software company, or are driving your own start-up, if you are building Android apps, you need to attend AnDevCon, March 7-9, 2011 in San Francisco."

  • Coach Wally's Season Begins Tonight

    Coach Wally's Season begins tonight.  There is no truth to the rumor that I have been suspended by the SEC, ACC, or Big10 networks.  Practice starts at 7:30 pm.

    Posted Dec 02 2010, 10:31 PM by wallym with no comments
    Filed under:
  • Code PaLOUsa 2011

    Code PaLOUsa 2011

    Code PaLOUsa is a two-day, eight-track software development conference in Louisville, KY on March 4-5, 2011 designed to cover all aspects of software development regardless of technology stack. We will have sessions revolving around Microsoft, Java, Ruby, PHP, and Clojure; along with sessions on higher, platform-agnostic levels. There will be 60 technical presentations and panel discussions from well-known professionals in the software development community and a keynote talk from Douglas Crockford of Yahoo! and JavaScript/JSON fame.

    The tracks for Code PaLOUsa 2011:

    • Architecture:  SOA, W3C standards, WS* implementations, interoperability, and all things 30,000 feet or higher
    • Cloud:  All things about the cloud, including the who, what, where, when, why, and how about cloud computing
    • Desktop Development:  Standard applications, fat/smart client, client/server, and all things running local on Windows, Mac, or Linux
    • Web Development:  Web services, Ajax frameworks, and all things related to the browser
    • Methodologies:  Anything pertinent to how modern development methodologies help build software faster, cheaper, and better
    • Mobility:  All things mobile - platforms, devices, content distribution, social networking, community building, and anything else used in conjunction with those devices which have small screens
    • Languages:  Discussions on what's new and cool in software development languages such as C#, Java, PHP, Python, Ruby, Visual Basic, etc.
    • Entrepreneur:  Discussions about how to start your own technology company or continue to successfully run your existing technology company

    For more information about our conference to include the complete schedule and registration information, check out http://www.codepalousa.com/.  You can also get timely updates by following @CodePaLOUsa on Twitter.

    Register Now!
2006 - Wallace B. McClure
Powered by Community Server (Non-Commercial Edition), by Telligent Systems