Continuous paging in Windows Phone 7

Here’s a quick and dirty implementation of continuous paging with Windows Phone 7. These code snippets are from a project using the GalaSoft MVVM Light Toolkit and Ninject, however you can adapt to fit your model. The paging and data binding functionality is abstracted in the base class PagedListViewModelBase so that the paging functionality can be easily applied to different kinds of lists – the lists inherit from PagedObject, which has a NumberOfResults property.

XAML:

 

XAML.cs:

private void profiles_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ((SomeViewModel)(this.DataContext)).RowTouchedCommandHandled(e); // this just calls the method in the viewmodel - you can call it directly if your aren't using MVVM
        }

SomeViewModel.cs: inherits from PagedListViewModelBase

/// This is the only view-specific code you need for rendering and paging.  All the paging and databinding is handled by PagedListViewModelBase
/// SelectionChanged handlers can go here or in the base class
 public override void GetDataFromWebService(object obj)
        {
            // Get Data:
            if (!IsLoading)
            {
                IsLoading = true;
                var svc = new ProfileWebService(_userService.Current(), webService);
                svc.GetSearchResults(CurrentPage, OnItemsRetrieved);
            }
        }

PagedListViewModelBase.cs: contains the databinding and paging functionality

protected ObservableCollection _pagedObjectList;
 
// An ObservableCollection object generates NotifyPropertyChanged events to let the UI know when to update
 public ObservableCollection PagedObjectList
        {
            get
            {
                if (_pagedObjectList == null && !IsLoading)
                {
                    if (!IsInDesignMode)
                    {
                        GetDataFromWebService(null);
                    }
                    else
                    {
                        // design mode
                        GenDesignTimeMockProfiles();
 
                        RaisePropertyChanged("PagedObjectList");
                    }
                }
                return _pagedObjectList;
            }
            set
            {
                _pagedObjectList = value;
            }
        }
 
protected int CurrentPage { get; set; }
protected bool IsLoading;
 
        ///  Handles touches from user and decided when to add the next page to the list
       public void RowTouchedCommandHandled(MouseButtonEventArgs obj)
        {
            var personalProfile = ((PagedObject)(((FrameworkElement)obj.OriginalSource).DataContext));
 
            if (personalProfile.GetType() != typeof(PersonalProfile))
                return;
 
            int index = PagedObjectList.IndexOf(personalProfile);
            Debug.WriteLine("Current index: " + index);
            Debug.WriteLine("NumberOfResults: " + personalProfile.NumberOfResults);
 
            if (!IsLoading && personalProfile.NumberOfResults > PagedObjectList.Count && index > PagedObjectList.Count - 6) // if less than six items from the end, get the next page
            {
                CurrentPage += 1;
                Debug.WriteLine("Next page: " + CurrentPage);
                GetDataFromWebService(0);
            }
        }
 
 
public abstract void GetDataFromWebService(object obj);        
 
  protected void OnItemsRetrieved(List pagedObjects, Error error)
        {
            if (error == null)
            {
                if (_pagedObjectList == null)
                {
                    _pagedObjectList = new ObservableCollection();
                }
                pagedObjects.ForEach(p => _pagedObjectList.Add(p));
 
                RaisePropertyChanged("PagedObjectList");
                IsLoading = false;
            }
            else
            {
                Error = error;
            }
        }
    }
 
/// You don't need all these conversions if you use a single type for your lists.            
/// .Net 4.0 adds support for co-variance, which allows casting a generic collection to base type
 protected void OnItemsRetrieved(List profileList, Error error)
        {
            var objList = new List();
            profileList.ForEach(objList.Add);
            OnItemsRetrieved(objList, error);
        }

PagedObject.cs:

[DataContract]
    public class PagedObject : ModelBase
    {
        /// <summary>
        /// Total number of results for this search
        /// </summary>
        [DataMember]
        public int NumberOfResults { get; set; }
    }

Using Reflection to serialize DTO’s

Suppose that you have a DTO (data transfer object) that you want to convert into a parameter array to be saved to file or sent over the web. You could serialize it and convert it to XML or JSON. But maybe you want to send it in an HTTP POST or GET and you don’t want to know anything about the class itself. You could use Reflection to iterate through the properties and extract the property names and values and output them to a string.

For example, this code will convert a class into a string suitable for a REST API call:

var properties = prefs.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
 
           properties.ToList().ForEach(property =&gt;
                                           {
                                               var hasDataMemberAttribute = property.GetCustomAttributes(typeof(DataMemberAttribute), false);
                                               if (hasDataMemberAttribute.Length == 1)
                                               {
                                                   string name = property.Name.ToLower();
                                                   string value = String.Empty;
 
                                                   object objValue = property.GetValue(prefs, null);
                                                   if (null != objValue)
                                                       value = objValue.ToString();
 
                                                   // Only serialize properties marked with the [DataMember] attribute:
                                                   var hasBrokerMapAttribute = property.GetCustomAttributes(typeof(DataMemberBrokerMapAttribute),
                                                                                                            false);
                                                   if (hasBrokerMapAttribute.Length == 1)
                                                   {
                                                       name = ((DataMemberBrokerMapAttribute)hasBrokerMapAttribute[0]).Key;
                                                   }
 
                                                   if (value.Length &gt; 0)
                                                   {
                                                       filter.Append(String.Concat("/", name, "=", value));
                                                   }
                                               }
 
                                           });
 
           Debug.WriteLine("Search Filter:" + filter);
           return filter.ToString();

Getting an OpenSocial user’s GPS coordinates with YQL

This code is designed to run inside a Yahoo Open App, but it can be adapted for any OpenSocial widget written with the JavaScript API. It uses OpenSocial to get the users unstructured location and YQL to convert it into GPS coordinates.

Continue reading “Getting an OpenSocial user’s GPS coordinates with YQL” »

Rotating content with JQuery, JTemplates & AJAX

The following JavaScript is used here to rotate the featured product every 30 seconds. I will leave the implementation of the JSON-emitting REST api for another post.

<!--mce:0-->
<!--mce:1-->    
 
<!--mce:2-->
<div class="outerbox"></div>
<textarea> 
&lt;div class="outerbox"&gt;
&lt;div class="box featured"&gt;
&lt;h2 &gt;
                        Featured&lt;/h2&gt;
&lt;div class="item"&gt;
&lt;div class="bord-se"&gt;
&lt;div class="bord-ne"&gt;
&lt;div class="bord-s"&gt;
                                                &lt;a href="/store/Product.aspx?ProductId={$T.ProductId}&amp;utm_source=Homepage&amp;utm_medium=FeaturedProd&amp;utm_term=Widget&amp;utm_campaign=Featured_Widget" mce_href="/store/Product.aspx?ProductId={$T.ProductId}&amp;utm_source=Homepage&amp;utm_medium=FeaturedProd&amp;utm_term=Widget&amp;utm_campaign=Featured_Widget" id="A1"&gt;
                                                        &lt;img class="FeaturedProduct" src="{$T.ThumbnailUrl}" mce_src="{$T.ThumbnailUrl}" alt="featured" style="border-width:0px;" mce_style="border-width: 0px;" /&gt;
                                                &lt;/a&gt;
                                        &lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;h4&gt;
                        &lt;a href="/store/Product.aspx?ProductId={$T.ProductId}&amp;utm_source=Homepage&amp;utm_medium=FeaturedProd&amp;utm_term=Widget&amp;utm_campaign=Featured_Widget" mce_href="/store/Product.aspx?ProductId={$T.ProductId}&amp;utm_source=Homepage&amp;utm_medium=FeaturedProd&amp;utm_term=Widget&amp;utm_campaign=Featured_Widget"&gt;{$T.Name}&lt;/a&gt;&lt;/h4&gt;
 
                        &lt;span&gt;Author: &lt;/span&gt;
                        &lt;a href="/store/search.aspx?m={$T.AuthorId}" mce_href="/store/search.aspx?m={$T.AuthorId}"&gt;{$T.Author}&lt;/a&gt; 
                        &lt;span class="Price"&gt;
                                ${$T.Price}&lt;/span&gt; 
 
            {$T.Summary}                                
 
                        &lt;a class="more" href="/store/New-Products-C52.aspx" mce_href="/store/New-Products-C52.aspx"&gt;view all…&lt;/a&gt;
 
&lt;/div&gt;
&lt;/div&gt;
 
</textarea>

AES encryption strategies with .Net

I did a presentation last week on AES encryption techniques in .Net.

I’ll post some details here later, but for now, I’ve uploaded a zip file with the project code.

Here’s the key bit:

 
            string key = "1234567891123456";
            string secret = @"This is a secret.";
 
            Console.WriteLine("basic:");
            EncryptString(key, secret);
            Console.ReadKey();
 
            Console.WriteLine("salt the secret:");
            // good when there are multiple machines but a dynamic global shared secret (for example, Profile Create Date or User ID)
            string secret2 = secret + " ###" + DateTime.Now.Millisecond;
            EncryptString(key, secret2);
 
            secret2 = secret + " ###" + DateTime.Now.Millisecond;
            EncryptString(key, secret2);
 
            Console.ReadKey();
 
            Console.WriteLine("salt the key:"); 
            // good when the same machine encrypts/decrepts
            string uniqueMachineIdentifier = MachineId.GetProcessorID();
            Console.WriteLine("MachineId: " + uniqueMachineIdentifier);
            EncryptString(key + uniqueMachineIdentifier, secret);
            Console.ReadKey();
 
            Console.WriteLine("SHA1 hash the passphrase with a salt:"); 
            // note: talk about why hashing is good
            SHA1 sha = new SHA1CryptoServiceProvider();
            // This is one implementation of the abstract class SHA1.
            string password = "this is my user password and/or userid";
            byte[] saltedKey = Encoding.Default.GetBytes(key + password);
 
            byte[] result = sha.ComputeHash(saltedKey);
            EncryptString(Convert.ToBase64String(result), secret);
            Console.ReadKey();

Using the MySql ADO.Net adapter

public DataSet ExecuteQuery(string commandText)
        {
            DataSet ds = new DataSet();
            using (var connection = new MySqlConnection(connString))
            {
                connection.Open();
                var command = connection.CreateCommand();
                command.CommandText = commandText;
                using (var data = new MySqlDataAdapter { SelectCommand = command })
                {
                    data.Fill(ds);
                    connection.Close();
                }
            }
            return ds;
        }

.Net Graphics: drawing text on a bitmap

I use this code here.

Graphics backgroundGraphics;
backgroundImage = (Bitmap)Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "\images\Header.jpg");
backgroundGraphics = Graphics.FromImage(backgroundImage);
var font = new Font("Perpetua Titling MT", 24F, FontStyle.Regular);
backgroundGraphics.DrawString(authorname.ToUpper(), font, new SolidBrush(Color.FromArgb(100, 0, 0, 0)), 10, 5);

Now save – or output to the browser:

backgroundImage.Save(context.Response.OutputStream, ImageFormat.Jpeg);

Response.Redirect and 302 and 301 status codes

If you use Response.Redirect to direct users to a new location, you should be aware that it issues a status code of 302, which means that “the resource resides temporarily under a different URI.” If you intend to communicate that the resource has permanently changed locations, you should not use Response.Redirect. This is important for search engines and other crawlers that might need to know the definitive url.

To send a 301 redirect:

Response.Status = "301 Moved Permanently";
Response.StatusCode = 301;
Response.AddHeader("Location", url);
Response.End();

Update: ASP.Net 4.0 ads a Response.RedirectPermanent() method.