Friday, May 16, 2014

Theme resources for Windows Phone

List of all the windows phone predefined resources.

http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff769552(v=vs.105).aspx#BKMK_TextStyles

an object of the type cannot be applied to a property that expects the type system.windows.data.ivalueconverter

Had a converter class to handle conditional formatting of a xaml field.  Could not
figure out why I was getting compilation errors.

Converter needs to receive a resource that implements IValueConverter interface

<YourClass>Converter needs to implement IValueConverter.

Conditional element in xaml depending on the binding content

Problem:

 I was trying to hide and expose information in xaml form.  The Address should not display if it is empty.
<TextBlock Text="{Binding Path=Address}" />


Solution:

<TextBlock Text="{Binding Path=Address}" Visibility="{Binding Path=Address, Converter={StaticResource StringLengthVisibilityConverter}" />

Create helper class and reference in the xaml.

 public class StringLengthVisiblityConverter: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null || value.ToString().Length == 0)
        {
            return Visibility.Collapsed;
        }
        else
        {
            return Visibility.Visible;
        }
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Don't need to implement this
    }
}





Source:
http://stackoverflow.com/questions/4450866/conditional-element-in-xaml-depending-on-the-binding-content

The property 'VisualTree' is set more than once

I was trying to design a template for binding a collection and was getting this error when I tried
to Bind text block to the property. 

Problem:
I could not get this to compile it kept throwing the error. - The property 'VisualTree' is set more than once

<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
    
<Label Grid.Column="0" Content="{Binding Path=Type}" />
<TextBox Grid.Column="1" Text="{Binding Path=CountryPrefix}" />
<TextBox Grid.Column="2" Text="{Binding Path=Number}" />
     
  </DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>


Solution:

I was missing the layout panel, ie. StackPanel

<ItemsControl ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Label Grid.Column="0" Content="{Binding Path=Type}" />
<TextBox Grid.Column="1" Text="{Binding Path=CountryPrefix}" />
<TextBox Grid.Column="2" Text="{Binding Path=Number}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

Tuesday, May 13, 2014

Sending email from Arvixe server

Problem:
How do I configure Arvixe server to send email from my website

Solution:
System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
eMail.IsBodyHtml = true;
eMail.Body = body;
eMail.From = new System.Net.Mail.MailAddress(fromEmail);
eMail.To.Add(toEmail);
eMail.Subject = subject;
System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient();

SMTP.Credentials = new System.Net.NetworkCredential("user","pass");
SMTP.Host = "localhost";
SMTP.Send(eMail);

Source
http://forum.arvixe.com/smf/programming-questions-tutorials/how-to-send-asp-net-email-using-system-net-mail/

Windows Phone 8 photo/image resizing


Problem:

I am trying to wrap up my first phone application which submits text and photos to an email server.
I wanted to control file size since the user can send anything on their phone.  I had been using the BitmapImage captured directly from the e.ChosenPhoto Task.  There are a number of great tutorials on basic photo capturing.  What they overlook is the the whole resizing issue.   The object for that is WriteableBitmap but you can't just cast the BitmapImage to WriteableBitmap.

The BitmapImage is pretty much immutable once you create it.  That is there is no implicit cast to an object like WriteableBitMap.  Most solutions involve reading the content of the BitmapImage as a stream or array into an image and then casting to to WriteableBitmap.


Solution 1:

Mike Ormond's post was very helpful.  He used a memory stream and saved the resulting byte array to the MediaLibrary.

void task_Completed(object sender, PhotoResult e)
{
  if (e.Error == null)
  {
    BitmapImage bi = new BitmapImage();
    bi.SetSource(e.ChosenPhoto);
    Image image1 = new Image()
    {
      Width = 800,
      Height = 600,
      Visibility = System.Windows.Visibility.Collapsed,
      Source = bi
    };
    ScaleTransform st = new ScaleTransform()
    {
      ScaleX = 0.1,
      ScaleY = 0.1
    };
    WriteableBitmap wb = new WriteableBitmap(image1, st);
    ThreadPool.QueueUserWorkItem(callback =>
    {
      MemoryStream ms = new MemoryStream();
      wb.SaveJpeg(ms, 80, 60, 0, 80);
      using (MediaLibrary lib = new MediaLibrary())
        lib.SavePicture("Test", ms.ToArray());
    });
  }
}

Solution 2:
Take the resulting source photo directly to a WriteableBitmap.


WritableBitmap bitmap = new WritableBitmap(); //Use appropriate constructor
bitmap.SetSource(e.ChosenPhoto);
or

ScaleTransform st = new ScaleTransform()
{
ScaleX = 0.1,
ScaleY = 0.1
};
WriteableBitmap wb = new WriteableBitmap(e.ChosenPhoto, st);

Source:
http://msdn.microsoft.com/en-us/library/dd638675(v=vs.95).aspx
http://stackoverflow.com/questions/8252001/wp7-5e-chosenphoto-issue

 Solution 3:

public void DecodePhoto(byte[] byteVal)
        {
            if (byteVal == null) return ;

            try
            {
                MemoryStream strmImg = new MemoryStream(byteVal);
                BitmapImage myBitmapImage = new BitmapImage();
                myBitmapImage.BeginInit();
                myBitmapImage.StreamSource = strmImg;
                myBitmapImage.DecodePixelWidth = 200;
                myBitmapImage.EndInit();
                MugShot.Source = myBitmapImage;
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }
        }
Source:
http://stackoverflow.com/questions/8897210/byte-to-bitmapimage
http://stackoverflow.com/questions/14718855/how-to-create-writeablebitmap-from-bitmapimage

Writable bit map SDK

https://www.blogger.com/blogger.g?blogID=8256225704949716108#editor/target=post;postID=5955005466364600781

http://stackoverflow.com/questions/5774038/resizing-resulting-camera-stream

Monday, May 12, 2014

Friday, May 9, 2014

How to configure SMTP client to post to directory

Problem:
Needed to set up a webform to post email to a directory vice sending the email.
It is pretty straightforward.
 
Solution:
 
var smtpClient = new SmtpClient();
//Specify the delivery method as pickup
smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
//Specify folder for the pickup.
smtpClient.PickupDirectoryLocation = pickupFolder;
 
Source:

Wednesday, May 7, 2014

Isolated Storage Explorer for windows phone 8

How to use the Isolated Storage Explorer tool for Windows Phone 8
http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh286408(v=vs.105).aspx

Isolated Storage Explorer is installed in the following location:
Program Files (x86)\Microsoft SDKs\Windows Phone\v8.0\Tools\IsolatedStorageExplorerTool



Focus on section Isolated Storage Explorer examples


ISETool.exe ts xd f8ce6878-0aeb-497f-bcf4-65be961d4bba c:\data\myfiles
 
Downloads the local folder content of the app from the default emulator to the C:\data\myfiles\IsolatedStore folder on the computer.
 
The tool creates the IsolatedStore folder under the directory that you specify.
 

OptionDescription
cmd[:param]
cmd optionDescription
ts(Take snapshot) Copies the files and directories in the local folder from the device or emulator to your computer.The ts option copies the folders and files to an IsolatedStore folder that it creates on your computer under the target folder that you specify. The ts option also creates the following subdirectories in the IsolatedStore folder that it creates in the target directory.

rs
(Restore snapshot) Replaces the files and directories in the local folder on the device or emulator with files and directories from your computer.
Caution noteCaution:
If you use the rs option to upload folders and files that you downloaded previously by using the ts option, make sure that you specify the IsolatedStorage folder created on your computer by the ts option as the source folder for the rs option.
dir[:device-path]Lists the files and directories in the specified directory of the local folder. If a directory is not specified, the files and directories in the root of the app’s local folder are listed. If no files or directories are found, an error is raised.Don’t include a leading or trailing slash in the directory entry.
EnumerateDevicesLists the valid device targets and the device index for each device.
target-device[:param]
target-device optionDescription
xdIndicates to target the emulator.
deIndicates to target a tethered device.
deviceindex:nIndicates to target the device listed at index n. To get the list of available devices, run the command ISETool EnumerateDevices.
product-idSpecifies the ProductID from the WMAppManifest.xml file for the app that you want to test.
desktop-pathSpecifies the directory on your computer where the local folder files are written to or copied from.
If the specified directory already exists, then a ts command overwrites the contents of the directory with no warning.
When you use the ts option to copy files from the emulator or device to the computer, the tool copies them to an IsolatedStore folder under the directory that you specify.

Quickstart: Working with files and folders in Windows Phone 8

Sample code for file and folder manipulation in Windows Phone.

http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj681698(v=vs.105).aspx

Calling Web API from a Windows Phone 8 Application

Robert McMurray has posted a great tutorial on the ASP.Net site from Microsoft.
It combines some APIs want to get a better handle on Web API, HttpClient and
the Windows Phone API


http://www.asp.net/web-api/overview/web-api-clients/calling-web-api-from-a-windows-phone-8-application

A System.Resources.MissingManifestResourceException exception occurs when you try to access a localized resource

Problem:
I broke my phone app out into different projects and now have BLL logic in a separate project.  I created a windows phone class library but it did not include the ever handy resources file in the template.  I foolishly copied and pasted from another project into the new project.  I ended up with this error.  This caused me to do some research into this as of yet unknown area to me. 

The resources file was designed primarily to be used for interationalizing projects.  You can create a resource file for each culture in your project.  This way you can share the same enumerations across the project and simply load the page with the resource which matches the culture of the persons brower. 

My mistake was to try and create this by copy and paste.  If you want to do this manually then microsoft provides great instructions on building Satellite assemblies.



The following Al.exe command creates a satellite assembly for the application MyApp from the file strings.de.resources.

al /t:lib /embed:strings.de.resources /culture:de /out:MyApp.resources.dll

Solution:
I simply dropped the resources file and use the add resource element to the project in question.



Source:

http://support.microsoft.com/kb/839861
Creating Satellite Assemblies
http://msdn.microsoft.com/en-us/library/21a15yht(v=VS.100).aspx


How to do a multipart post with file upload using WebApi HttpClient

Problem:  My app needs to submit a user form to a web backend.  There are a number
of easy ways to do this via the WP8 SDK to upload files.  These are all done pretty much
with GETs vice POSTS.  I looked around for some solutions to do a multipart submittal since
my form will have files as well as text to submit. The only issue is getting the files as byte arrays.
I will do a post on this particular issue at another time.



Solution:

Form:

     <form action="/api/workitems" enctype="multipart/form-data" method="post">
        <input type="hidden" name="type" value="ExtractText" />
        <input type="file" name="FileForUpload" />
        <input type="submit" value="Run test" />
    </form>


Code behind
 using (var client = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        var values = new[]
        {
            new KeyValuePair<string, string>("Foo", "Bar"),
            new KeyValuePair<string, string>("More", "Less"),
        };
        foreach (var keyValuePair in values)
        {
            content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
        }
        var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName));
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "Foo.txt"
        };
        content.Add(fileContent);
        var requestUri = "/api/action";
        var result = client.PostAsync(requestUri, content).Result;
    }
}

Source:
http://stackoverflow.com/questions/10339877/asp-net-webapi-how-to-perform-a-multipart-post-with-file-upload-using-webapi-ht

Tuesday, May 6, 2014

ICloneable not available for Windows Phone 8.

Problem:
I was trying to create a "copy" of an object in memory within .Net framework.  I ran headlong into the stack vs. heap storage.  When I tried to "copy" the parent object to a child object each time I updated the child the parent was also updated.  This is occurring because of the Framework memory management defaults.  The child object is a reference to the parent.  What I need is to clone the object.

Potential Solutions:

Source:
http://www.c-sharpcorner.com/UploadFile/rmcochran/chsarp_memory401152006094206AM/chsarp_memory4.aspx


Sample 1:


using System;

public class IdInfo
{
   public int IdNumber;

   public IdInfo(int IdNumber)
   {
      this.IdNumber = IdNumber;
   }
}

public class Person
{
   public int Age;
   public string Name;
   public IdInfo IdInfo;

   public Person ShallowCopy()
   {
      return (Person)this.MemberwiseClone();
   }

   public Person DeepCopy()
   {
      Person other = (Person)this.MemberwiseClone();
      other.IdInfo = new IdInfo(this.IdInfo.IdNumber);
      return other;
   }
}

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      // Create an instance of Person and assign values to its fields.
      Person p1 = new Person();
      p1.Age = 42;
      p1.Name = "Sam";
      p1.IdInfo = new IdInfo(6565);

      // Perform a shallow copy of p1 and assign it to p2.
      Person p2 = (Person)p1.ShallowCopy();

      // Display values of p1, p2
      outputBlock.Text += "Original values of p1 and p2:" + "\n";
      outputBlock.Text += " p1 instance values: " + "\n";
      DisplayValues(outputBlock, p1);
      outputBlock.Text += " p2 instance values:" + "\n";
      DisplayValues(outputBlock, p2);

      // Change the value of p1 properties and display the values of p1 and p2.
      p1.Age = 32;
      p1.Name = "Frank";
      p1.IdInfo.IdNumber = 7878;
      outputBlock.Text += "\nValues of p1 and p2 after changes to p1:" + "\n";
      outputBlock.Text += " p1 instance values: " + "\n";
      DisplayValues(outputBlock, p1);
      outputBlock.Text += " p2 instance values:" + "\n";
      DisplayValues(outputBlock, p2);

      // Make a deep copy of p1 and assign it to p3.
      Person p3 = p1.DeepCopy();
      // Change the members of the p1 class to new values to show the deep copy.
      p1.Name = "George";
      p1.Age = 39;
      p1.IdInfo.IdNumber = 8641;
      outputBlock.Text += "\nValues of p1 and p3 after changes to p1:" + "\n";
      outputBlock.Text += " p1 instance values: " + "\n";
      DisplayValues(outputBlock, p1);
      outputBlock.Text += " p3 instance values:" + "\n";
      DisplayValues(outputBlock, p3);
   }

   public static void DisplayValues(System.Windows.Controls.TextBlock outputBlock, Person p)
   {
      outputBlock.Text += String.Format(" Name: {0:s}, Age: {1:d}", p.Name, p.Age) + "\n";
      outputBlock.Text += String.Format(" Value: {0:d}", p.IdInfo.IdNumber) + "\n";
   }
}
// The example displays the following output:
// Original values of p1 and p2:
// p1 instance values:
// Name: Sam, Age: 42
// Value: 6565
// p2 instance values:
// Name: Sam, Age: 42
// Value: 6565
//
// Values of p1 and p2 after changes to p1:
// p1 instance values:
// Name: Frank, Age: 32
// Value: 7878
// p2 instance values:
// Name: Sam, Age: 42
// Value: 7878
//
// Values of p1 and p3 after changes to p1:
// p1 instance values:
// Name: George, Age: 39
// Value: 8641
// p3 instance values:
// Name: Frank, Age: 32
// Value: 7878
Source:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/system.object.memberwiseclone(v=vs.105).aspx


Whilst the standard practice is to implement the ICloneable interface (described here, so I won't regurgitate), here's a nice deep clone object copier I found on The Code Project a while ago and incorporated it in our stuff.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

/// <summary>
/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
/// Provides a method for performing a deep copy of an object.
/// Binary Serialization is used to perform the copy.
/// </summary>
public static class ObjectCopier
{
    /// <summary>
    /// Perform a deep Copy of the object.
    /// </summary>
    /// <typeparam name="T">The type of object being copied.</typeparam>
    /// <param name="source">The object instance to copy.</param>
    /// <returns>The copied object.</returns>
    public static T Clone<T>(T source)
    {
        if (!typeof(T).IsSerializable)
        {
            throw new ArgumentException("The type must be serializable.", "source");
        }

        // Don't serialize a null object, simply return the default for that object
        if (Object.ReferenceEquals(source, null))
        {
            return default(T);
        }

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new MemoryStream();
        using (stream)
        {
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }
}



Now the method call simply becomes objectBeingCloned.Clone();.

Source:
http://stackoverflow.com/questions/78536/deep-cloning-objects-in-c-sharp

Windows Phone 8 - How to get a certain IsolatedStorageSetting Key

Problem

I was puzzling over this issue due to isolated storage which I am using on one of my applications.
I need to retrieve a setting from storage but was could not assume that the key exists.  If I attempted to query a null value then I would get an error. 

Solution

ICollection<string> sKeys = (ICollection<string>) IsolatedStorageSettings.ApplicationSettings.Keys
if(!sKeys.Contains(AppResources.SavedReportKeyName))
{
//Create key in isolated storage
}


Source:
http://social.msdn.microsoft.com/Forums/wpapps/en-US/529d6dad-fcfe-4609-9a64-097dcd0bae33/how-to-get-a-certain-isolatedstoragesetting-key?forum=wpdevelop