March 2009 - 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

March 2009 - Posts

  • Codestock Session Submissions

    If you are not familiar with it, CodeStock is June 26-27 in Knoxville, TN.  If you have not submitted your talk, do so now.  Run, don't walk over to http://www.codestock.org/Speakers.aspx and submit your session.  Session submissions are due by the end of today (March 31).

  • More things that I have learned with Azure

    I've been working on this application to run on Windows Azure.  I wanted to share a few things that I have learned.  I'm not sure if I have missed these being covered else where, but I want to bring them up here for my own knowledge.  I find that I remember things much better if I blog them than if I put them on twitter.

    • Resource not found for the segment 'ObjectTableName." Steve Smith has a good blog post on this at http://stevesmithblog.com/blog/azure-table-storage-gotcha/.  I got this message, followed Steve's instructions and bang, still go the message.  WTF is that about!  Anyway, I found that I had to reset the table storage through the azure development storage applet and then recreate the tables from the objects in Visual Studio.  Once I did that, things seemed to work better.  Yippee!
      Another note, that you can get this error when you operate on a LINQ query that returns no objects.
    • I was running queries that were not returning any data.  WTF is that about! Then it hit me, LINQ doesn't return data until you actually ask for that data.  I need to force LINQ to send me some data in some situations.  How can I force this to occur?  I saw that some of my queries were returning data and some were not.  I started playing around and found that if I called .ToList<T>() after my query that the data always came back to me.  I figure that was a step in the right direction.
    • Azure Development Tools use Sql Server Express on the local development machine to store data during development.  I decided to look and see what is happening.  Guess what, you can connect up and see your data just like you thought you could in any application.  Also, you can use Sql Server tools to see WTF is going on.  I used that to figure out the issue above.
      Sql Express in Azure
    • DateTime.Now vs. DateTime.UtcNow.  Have you used DateTime.Now in an Azure query?  It works just fine when you are running in the local development fabric.  Deployed to the azure hosted fabric and I got an error.  You can't quite connect VS.NET to the hosted fabric to see what is going on.  After lots of testing, I changed the query I was doing to use DateTime.UtcNow and low and behold my app started posting messages to twitter from the hosted fabric.
  • eTag error in Windows Azure

    Have you gotten this type of error in Windows Azure:

    Since entity type 'ObjectName' has one or more etag properties, If-Match HTTP header must be specified for DELETE operations on this type.

    If so, the fix is really simple.  The problem is that you have created a new object and are trying to stuff it back into your entities.

    My code to resolve this looks like this:

            public void TwitterEntryDelete(string PartKey, string RowKey)
            {
                TwitterEntry te = new TwitterEntry()
                {
                    PartitionKey = PartKey,
                    RowKey = RowKey
                };
                AttachTo("TwitterEntries", te, "*"); // <--  The final parameter is the key to solving the problem. You need to tell EF to disregard where this object came from and to put the object into the collection.
                DeleteObject(te);
                SaveChanges();
            } 

    By disregarding where the object came from, we can go ahead and tell the system to put the object in our collection(attach) and then operate on the object.

  • More reminders / gotchas from the trenches with Azure

    I've been working on setting up my VPC for Azure's March CTP.  This is a fresh install.  I had everything installed.  Here are a couple of gotchas that you have to remember:

    • SqlExpress needs to be running.  I had the .\SqlExpress service turned off in my archived vpc.  With the service off, the dev tools can't see the database service so they fail.
    • Create TablesA database can be setup by right clicking on your cloud service and selecting "Create Test Storage Tables."
    • With a new installation, windows communication foundation (WCF) is most likely not setup.  You may need to setup calls to WCF.  To setup WCF, you may need to login as an Administrator and run "ServiceModelReg -i"
  • ASP.NET 4.0 AJAX - Caching Data on the client

    One of the interesting new objects in ASP.NET 4.0 AJAX is the DataView.  its a client side object which is associated with a display tag of some type.  In my examples, I've been using a table.  I assume it could be anything.  One of the features of the DataView is the ability to call an event each time a record is bound to the DataView.  This is similar in concept to the server side asp.net grids which have the OnRowDataBound events (or similarly named).  One of the common scenarios that I see is to have a drop down list box inside of a record.  This could represent typically anything.  As I was working through the DataView, I thought about some type of efficient way to cache the data.  In my scenario, the data is constant across the rows, so caching it is fairly easy.  Anyway, here goes:

    1. I call the method to get my data first before doing anything else in my page load client side event:
              TwitterService.GetFriends(userName, StoreFriendsCallBack);
              TwitterService.GetUserTimeLine(userName, TwitterServiceCallBack, TwitterServiceFailure);
    2. In side of my StoreFriendsCallBack method, all I do is store my data to a global js variable I call dd.
          function StoreFriendsCallBack(result) {
              dd = result;
          }
    3. Finally, I test to see if my dd (dropdown) object has any data or not.  If it has data, I use it, if not, then I go ahead and call back to the server to get my data.
              if (dd == null) {
                  TwitterService.GetFriends("More_Wally", FriendsCallBack, null, userCtx);
              }
              else {
                  DisplaySelect(dd, userCtx);
              }
  • ASP.NET 4.0 Preview 4 works fine in other browsers

    When I first worked with the original ASP.NET 2.0 AJAX, some folks told me that it only worked with IE, which was wrong then.  I decided to take a look at ASP.NET 4.0 Preview 4 in Chrome and Firefox.  I looked at my an example dataview i'm working with in my azure application.  Low and behold, it looked the same in IE8, Firefox 3, and Chrome 2 beta.  Here's a display of all of them.

    IE8:

    ASP.NET 4.0 Preview 4 in IE8 

    Firefox 3:

    asp.net 4.0 ajax preview 4 in FF

    Chrome 2 beta:

    asp.net 4.0 preview 4 in chome 

    There may be something that doesn't work right outside of IE, but I haven't seen it so far.

  • Twitter API - Submit a post in C#

    I used C# and WCF, but I could have just as easily used an ASMX web service.  This code is fairly simple.  No I didn't write it initially.  I found it online (Hey, we all have to start somewhere).  I massaged it a little to fit my needs and boom, here it is.  I have decided to leave the comments for the original code sample in the post.  Note: This code will not run as listed.  You have to have a password.  This code has that as a shared variable, but I'm not showing that to you, seriously.  I hope that this is of some help to you.

            [OperationContract]
            public void SubmitUserStatus(string username, string tweet)
            {
                // encode the username/password
                string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
                // determine what we want to upload as a status
                byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet);
                // connect with the update page
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
                // set the method to POST
                request.Method = "POST";
                // thanks to argodev for this recent change!
                request.ServicePoint.Expect100Continue = false;
                // set the authorisation levels
                request.Headers.Add("Authorization", "Basic " + user);
                request.ContentType = "application/x-www-form-urlencoded";
                // set the length of the content
                request.ContentLength = bytes.Length;
                // set up the stream
                Stream reqStream = request.GetRequestStream();
                // write to the stream
                reqStream.Write(bytes, 0, bytes.Length);
                // close the stream
                reqStream.Close();
            }

  • Windows Azure Samples - Storage Client and ASP.NET Providers

    I got my dev vpc setup and installed this evening.  I was pulling my hair out looking for the latest StorageClient and ASP.NET Providers.  Where the heck are they.  Well, their are in the Windows Azure SDK directory.  they are in the samples.zip file.  I missed it because it was in a zip file.

  • ASP.NET 4.0 AJAX - Dynamic update to the DOM

    As I was doing my talk on Saturday at the Atlanta Code Camp on data binding at the Atlanta Code Camp, there was a question about the  DOM being updated.  The question arose wondering if the DOM itself was really being updated.  Thanks to Paul Lockwood, he said that Firebug in Mozilla could tell us if it was being updated or not.  I pulled out FF 3 with Firebug, opened the page, started to drill through the code, and bang, there was the grid.  I did not know that Firebug had that feature.  Thanks to Firebug for showing that and thanks to the ASP.NET AJAX team for dynamically updating the DOM.

     

    dynamic dom 

    PS. My buddy Dave Ward told me that it's possible for Firebug to display DOM changes only.

  • Twitter API - Sending a Direct Message in C#

    I tried writing some code to send a direct message using the Twitter API. It was a FAIL.  I did some searching in google, and found this method below listed in a google group.  I didn't write it, but it works, so enjoy.  I plugged the method into my WCF Service and it just worked.

             [OperationContract]
            public void DMSend(string username, string recipient, string tweet)
            {
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://twitter.com/direct_messages/new.xml?user=" + recipient + "&text=" + tweet);
                req.Method = "POST";
                req.Credentials = new NetworkCredential(username, password);
                req.ContentLength = 0;
                req.ContentType = "application/x-www-form-urlencoded";
                WebResponse response = req.GetResponse();
            }

  • Why am I writing against the Twitter API directly?

     Yeah, so some of my friends asked me why I am not using a twitter library instead of calling the api directly.  Yeah, I'm wondering that to.  Seriously, the reason why I am doing that is that .net libraries to call out to twitter that I tried under VS 2008, did not work with Windows Azure. These libraries seemed to generate a security exception.  Given azure's security requirements being a little more than regular asp.net, I decided to just drop the search for a library and make my calls on my own.  Not sure if its a good decision or not, but its what I did.

    PS. I hear that Full Trust and Native Code support are coming to Azure.

  • Twitter API - Get a list of your friends in C#

    I needed to call the Twitter API and get a list of friends.  I thought I could do something similar to getting a list of posts, but alas, I had some stupid error in my linq to xml code.  I futzed around with it for days to no avail.  Finally, I decided it was just easier to iterate through the XML using an XmlNode and fill my objects that way.  Hey, it just worked.  Like my previous example, this code uses C# and is in a WCF Service.  Note: As displayed, the code doesn't work, you will have to supply a password.

            [OperationContract]
            public Friends[] GetFriends(string username)
            {
                string url = "http://twitter.com/statuses/friends.xml";
                string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                Friends frd;
                List<Friends> lf = new List<Friends>();

                request.Method = "POST";
                request.Credentials = new NetworkCredential(username, password);
                WebResponse response = request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string responseString = reader.ReadToEnd();
                reader.Close();
                XmlDocument xmld = new XmlDocument();
                xmld.LoadXml(responseString);
                XDocument document = XDocument.Parse(responseString);

                foreach(XmlNode xmln in xmld.SelectNodes("users/user"))
                {
                    frd = new Friends();
                    frd.id = Convert.ToInt32(xmln["id"].InnerText);
                    frd.name = xmln["name"].InnerText;
                    frd.screen_name = xmln["screen_name"].InnerText;
                    lf.Add(frd);
                }
                return (lf.ToArray());
            }
     

    My custom object which I am streaming back looks like this:

        [DataContract]
        public class Friends
        {
            [DataMember]
            public string name { get; set; }
            [DataMember]
            public string screen_name { get; set; }
            [DataMember]
            public int id { get; set; }
        }

  • Calling the Twitter API in C#

    I've been working on this application to send out tweets at a particular time.  One thing thing I want to do is be able to look at the logged in user's timeline.  I've been playing with the ASP.NET 4.0 AJAX Previews, so I thought I would marry the two.  As a result, I wrote the WCF code below in C#.  Note that the password is hidden, so the code won't work until you add that in.  Basically, I make a request to get the friends timeline.  This gives me the most recent 20 posts by default. I store the result in an XmlDocument.  I need to get that data out as a complex object of type UserStatusSvc as I am returning an array of that type.  I used Linq to Xml for that.

              [OperationContract]
            public UserStatusSvc[] GetUserTimeLine(string username)
            {
                string url = "http://twitter.com/statuses/friends_timeline.xml";
                //string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.Method = "POST";
                request.Credentials = new NetworkCredential(username, password);
                WebResponse response = request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string responseString = reader.ReadToEnd();
                reader.Close();
                XmlDocument xmld = new XmlDocument();
                xmld.LoadXml(responseString);
                XDocument document = XDocument.Parse(responseString);

                var query = from e in document.Root.Descendants()
                            where e.Element("user") != null
                            select new UserStatusSvc
                            {
                                UserName = e.Element("user").Element("screen_name").Value,
                                ProfileImage = e.Element("user").Element("profile_image_url").Value,
                                Status = HttpUtility.HtmlDecode(e.Element("text").Value),
                                StatusDate = e.Value.ParseDateTime().ToString()
                            };

                var users = (from u in query
                             where u.Status != ""
                             select u).ToList();

                return (users.ToArray());
            }

    Here's the definition of my UserStatusSvc object.

        [DataContract]
        public class UserStatusSvc
        {
            [DataMember]
            public string UserName { get; set; }
            [DataMember]
            public string ProfileImage { get; set; }
            [DataMember]
            public string Status { get; set; }
            [DataMember]
            public string StatusDate { get; set; }
        }

        public static class StringExtensions
        {
            public static DateTime ParseDateTime(this string date)
            {
                string dayOfWeek = date.Substring(0, 3).Trim();
                string month = date.Substring(4, 3).Trim();
                string dayInMonth = date.Substring(8, 2).Trim();
                string time = date.Substring(11, 9).Trim();
                string offset = date.Substring(20, 5).Trim();
                string year = date.Substring(25, 5).Trim();
                string dateTime = string.Format("{0}-{1}-{2} {3}", dayInMonth, month, year, time);
                DateTime ret = DateTime.Parse(dateTime);
                return ret;
            }
        }

    Thanks to Tim Heuer for some code he posted on his blog to get me started.  I have primarily stolen his code and reposted it here.  :-)

    PS. I modified this code example to remove the hokey CheckForNull(...).  It was stupid and not necessary.  I didn't realize I had left it in until I got hassled for it.  The line 'where Element("user") != null' resolved my problem.

  • Chattanooga .NET User Group on Tuesday March 17

     I'll be speaking at the Chattanooga .NET User Group on Tuesday March 17.  The topic is an introduction to asp.net ajax.

  • ASP.NET 4.0 AJAX - Pseudo Columns

    With the ASP.NET 4.0 AJAX previews, there is the concept of a pseudo column.  This is similar in concept to Oracle's rownum and rowid columns that are returned in a query.  The two columns that ASP.NET 4.0 AJAX when doing databinding are $index and $dataItem. 

    $index is an integer which represents the current record in the data binding operation.

    $dataItem are the columns that are available in the data binding operation.

More Posts Next page »
2006 - Wallace B. McClure
Powered by Community Server (Non-Commercial Edition), by Telligent Systems