Monday, December 2, 2013

Chrome v30 blocking HTTP Salesforce Web Tab

As of Chrome v30 if you have an http page configured as the URL in a Salesforce Web Tab you will be greated with a blank page.

Checking the developer console shows that the content has been blocked.

[blocked] The page at https://na5.salesforce.com/servlet/servlet.Integration?lid=01r700000000001&ic=1 ran insecure content from http://localhost:60000/site/SalesforceLanding.aspx?SessionId=00D70000000000….

The best solution is to switch the iframe page to use SSL (HTTPS) and you won't have any further issues.

If the iframe is only for development purposes you can temporarily bypass this security check using a small shield that appears on the right of the address bar and selecting "load unsafe script"

Friday, October 18, 2013

Importing the Salesforce Winter 13 Metadata API to .NET

After updating the Metadata API to v29.0 from v28.0 I started getting the following SGEN compilation errors:

  1. Error 25 Unable to generate a temporary class (result=1). D:\...\SGEN
  2. Error 26 Cannot convert type 'XYZ.SalesforceMetadata.QuickActionLayoutItem[]' to 'XYZ.SalesforceMetadata.QuickActionLayoutItem' D:\...\SGEN
  3. Error 27 Cannot convert type 'XYZ.SalesforceMetadata.QuickActionLayoutItem[]' to 'XYZ.SalesforceMetadata.QuickActionLayoutItem' D:\...\SGEN

The QuickActionLayoutItem complexType from the v29.0 wsdl:

   <xsd:complexType name="QuickActionLayout">
    <xsd:sequence>
     <xsd:element name="layoutSectionStyle" type="tns:LayoutSectionStyle"/>
     <xsd:element name="quickActionLayoutColumns" minOccurs="0" maxOccurs="unbounded" type="tns:QuickActionLayoutColumn"/>
    </xsd:sequence>
   </xsd:complexType>
   <xsd:complexType name="QuickActionLayoutColumn">
    <xsd:sequence>
     <xsd:element name="quickActionLayoutItems" minOccurs="0" maxOccurs="unbounded" type="tns:QuickActionLayoutItem"/>
    </xsd:sequence>
   </xsd:complexType>
   <xsd:complexType name="QuickActionLayoutItem">
    <xsd:sequence>
     <xsd:element name="emptySpace" minOccurs="0" type="xsd:boolean"/>
     <xsd:element name="field" minOccurs="0" type="xsd:string"/>
     <xsd:element name="uiBehavior" minOccurs="0" type="tns:UiBehavior"/>
    </xsd:sequence>
   </xsd:complexType>

The problem appears in the generated Reference.cs with the quickActionLayoutColumns multidimensional array return type.

        /// 
        [System.Xml.Serialization.XmlArrayItemAttribute("quickActionLayoutItems",
              typeof(QuickActionLayoutItem), IsNullable=false)]
        public QuickActionLayoutItem[][] quickActionLayoutColumns {
            get {
                return this.quickActionLayoutColumnsField;
            }
            set {
                this.quickActionLayoutColumnsField = value;
            }
        }

The XmlArrayItemAttribute typeof(QuickActionLayoutItem) should be typeof(QuickActionLayoutItem[]). After changing this manually the web reference compiled again.

        /// 
        [System.Xml.Serialization.XmlArrayItemAttribute("quickActionLayoutItems",
              typeof(QuickActionLayoutItem[]), IsNullable=false)]
        public QuickActionLayoutItem[][] quickActionLayoutColumns {
            get {
                return this.quickActionLayoutColumnsField;
            }
            set {
                this.quickActionLayoutColumnsField = value;
            }
        }

See also:

Saturday, September 14, 2013

TechEd 2013 Round Up / Summary

I've summarised some of the most interesting/important parts of my TechEd 2013 NZ notes here.

Keynote
AZR301 Building Real World Cloud Apps with Windows Azure - Part 1
  • Automate Everything (Everything that can be done in the Azure portal can be automated. Rest API. + Powershell commands. Azure script site with templates)
  • VS2013 has built in support for Git.
  • Continuous Integration and Delivery - http://tfs.visualstudio.com
  • Web DEV Best Practices
    • Scale out our web tier using stateless web servers. Dynamically scale our web tier based on actual usage load.
    • Multiple load balancers (Layer 7) can split requests to multiple VMs running IIS. Can handle server failure and start up a replacement VM. Lots of redundancy to handle failures.
    • Auto scaling rules based on time of day. Schedule times. Day or night for timezone. Logging shows scaling history.
    • 2 Core 4GB VM is a good starting point.
    • Instance count range and CPU load scaling.
    • Avoid using session state if possible. Prefer the cache provider if possible. Use CDN to edge cache static file assets. Use .NET 4.5 async to avoid blocking calls.
  • Single Sign on. - Windows Azure Active Directory (AD). Can be linked to on premise AD. Can be integrated with Salesforce. Wizard to setup sync all the users to the cloud.
  • Data Storage
    • SQL Database (Relational)
    • Table Storage (NoSQL Key/Value Store)- Advantage to store peta-bytes of data.
    • Blob Storage (unstructured files) – More like a standard file system.
    • Virtual Machines to host other options.
    • Slide – Data Storage Questions to Ask. Pros and Cons slide.
  • Data Scale and Persistence
    • Volume – MB/GB/TB/PB
    • Velocity – How quickly will it grow. Twitter – Fast data creation but only interested in most recent data.
    • Variety – Relational, images, key-value pairs, social graphs.
    • Scale out your data by portioning it.
    • Vertical Portioning. Split image data out of relational database into blobs.
    • Horizontal Portioning (Sharding). Split rows between databases based on some key (e.g. User last name).

ARC303 Hack-Ed: Wheedling and cajoling your way to success

Andy Prow and Kirk Jackson

  • Backtracking in RegEx can cause significantly increasing CPU workload. Reg Ex being used can be exposed client side with client side validation.
  • XmlDocument .Load expanding entities in the doc type. Can cause full CPU and rapidly expanding memory usage.
  • Cookies leaking out due to transitions via HTTP and HTTPS.
  • Wireshark. Exposes Client cookies sent over WIFI network.
  • File Upload Cheat Sheet - https://www.owasp.org/index.php/Secure_Coding_Cheat_Sheet#File_Upload
  • Highlighted Dapper SQL Injection Risks
Information Disclosure

Entity expansion is not limited to string literals though. It could very well refer to external data like the example below.

<!DOCTYPE doc [     
    <!ENTITY win SYSTEM “c:\windows\win.ini"> 
]> 
<doc> 
    &win; 
</doc>

If this document is somehow reflected back to the client it would result in disclosing information on the server that a client wouldn't have access to.


App202 Zero to Hundred - EventFinda comes to the Windows 8 store

Donnel Cyril and Mohit Singh

  • UI hidden is UI that doesn't exist. Primary controls on screen for search.
  • Incremental data loading. Lazy loading via ISupportIncremantalLoading to keep delays under 3 to 4 seconds.

DEV302 DevOps at LightSpeed, lessons we learned from building a Raygun

Jeremy Boyd and John-Daniel Trask

  • Octopus Deploy - Automated deployment to staging the production environments
  • Git - create a topic branch for any new task
  • ElasticSearch - for scaled search. Plus REST .NET API for interacting with it.
  • Redis - Out of process cache that can handle Key value pairs, queue data structures, hash structures

ARC305 Hack-Ed: Develop your Security Spidey-Sense

Andy Prow and Kirk Jackson

Indicators of potential security flaws in a website

  • Unlocked Vault
    • Dropping out of https to http - certain cookies should be marked to only send over https. Add Strict Transport Security header
      Strict-Transport-Security: max-age.
      Sesion abandoning on login. Especially from http to https
    • Password field with length and/or character limit - May indicate that it isn't being hashed and salted on storage.
    • Files that expose secret content (robots.txt, sitemap.xml)
    • Cached search engine results.
  • Too Trusting
    • Too many invalid password attempts. Use the brute force detection built into ASP.NET Membership Provider (max invalid password attempts, password attempt window)
    • Change password without entering existing password
    • Characters give errors, or display incorrectly: < ' " ; UTF smiley face.
    • Client only validation of user input.
    • User content displays directly on screen unescaped. <
    • No random tokens in the form data. CSRF
    • URLs are in the query string
    • SQL statements in the query string
  • Spilling your secrets - Information is being leaked out of the system.
    • Signup or password reset contains an existing password - should use one time URL for resetting password.
    • Site lists characters that are banned in text fields
    • Customer id (or similar object reference) in the URL
    • A number in the URL that increases by one (or in an obvious format)
    • You can tell the underlying technology
  • Back door is open - Front-door security is good but someone's left alternative avenues into the system.
    • Sensitive data is unencrypted
    • Authorisation - by URL or menu
    • Admin site available to the world - god mode. Separate God mode app.
    • Production data in a test environment. Dev laptop has production data / credit card details but no security of production.
  • D.I.Y Security
    • Doesn't use out of the box forms authentication
    • Custom single-sign-on
    • Home-built encryption
  • Dodgy Foundations - There is a poor underlying architecture or technology.
    • Mix of technologies (PHP and ASP.NET)
    • Cross-domain javascript / CSS
    • Rich Client components
    • Old OS, server, ASP.NET version
    • Built using Webforms
    • Writing directly to disk
  • Risky Business - Features requiring strong security have not been done
    • Application accepts file uploads
    • Parsing XML, HTML or other file formats
    • Credit card payments
    • Mobile app talking to API.

DEV304 C# on a diet with scriptcs

Glenn Block

  • Node.js - No IDE or project required. Minimal install
  • Microsoft Roslyn CTP - Compiler as a service
  • scriptcs - No IDE, project, class, namespace, Using statements
  • .csx is the Roslyn file extension.
  • http://choclatey.org/
  • #load to pull in seperate .csx
  • #r "System.Data"; // Get DLL out of GAC
  • using System.Data;
  • Visual Studio load in exe. Add - debug. Can be used to hit breakpoint.
  • Can be run standalone. REPL.
  • ScriptArgs[0] - access command line arguments. Anything after --
    Can be used to create full line command line tools.
  • scriptcs - install mongodb
    packages.config to pull dependancies
    Removes need for #r from GAC.
  • Script Packs - Require(); // Will discover from Packages folder. Skips need for using.
  • Hosting - Host scripts within an existing app.
  • http://github.com/scriptcs/scriptcs

Day Two


DEV305 Level up your API with Hypermedia

Amy Palamountain

Hypermedia.
Reduce the overhead of updates. Client can adjust to changes dynamically. No need to support older version of the API. Self navigation of API. Primary Concern. - Accessible - Consistent - Descriptive - Flexible - shield from breaking changes.

  • GET/POST/PUT/DELETE
    HEAD/PATCH/COPY/PURGE/LINK/UNLINK/OPTIONS

DEV306 10 F# Features Every C# Developer Should Crave

Ivan Towlson

  • F# match expression. No side affects to set the variable
  • immutability - Given by default in F#. Lots of extra effort in C# to hide behind Get only properties and equality overloading.
  • Discriminated Unions - Creating a parser. F# is more concise and isn't open to extension like the c# abstact base class.
  • non-nullable types
    f# types can't have null values (unless interop with other languages)
  • infix notation - Can only overload existing operators in C#. F# can define new ones.
  • Partial application
  • Pattern matching
  • Units of measure

APP308 Working with devices; integrating into peripherals for Windows 8 and Windows Phone.
  • 3D printing.
  • Location awareness
  • Fingerprint scanning. Biometrics instead of passwords.
  • Scan barcodes and read magnetic stripes. POS scanners.
  • Use geofence enter/exit to trigger app actions.
  • Manage virtual smart cards for remote.
  • Scan documents and images with scanners.
  • Bluetooth and low level USB. Native USB rather than relying on third party libraries.
  • Security - WinRT apps must declare deviceCapability. HID - humaninterfacedevice (emulates a keyboard for cammands). Does not require drivers. USB takes a more complicated payload.
  • New generic USB devices.
  • Bluetooth 4.0 GAP

APP309 Taking advantage of Windows 8.1
  • Use the canvas for the primary application buttons
  • AppBar hints similar to Windows Phone
  • Provide a great search experience inside the app. New dedicated control SearchBox
  • Snap view replaced by varible widths.
  • Moving past single screen and touch.
  • Kiosk mode
  • SpeechSynthesizer
  • Second screen support. ApplicationViewSwitcher.

XAML Dev differences

  • Flyouts.
  • SettingsFlyout
  • Input Controls Header control
  • DatePicker
  • PlacholderText
  • AppBarButton, toggle
  • CommandBar
  • PDFDocument. Get individual pages.
  • MediaElement. Includes playback controls. Embed YouTube.

DEV309 ASP.Net WebApi – Whats New

Open Web Interface for .NET (OWIN)

Attribute Routing

  • Removes need for configuring the routing in the config. Instead use the Route attribute. RoutePrefix to apply at the class level.
  • Special case routing with RegEx matching.
  • Routes stay with the code.
  • config.MapAttributeRoutes().
  • Helps avoid routing issues.

CORS

  • Cross Orgin Resource Sharing
  • Generally will only work with the newer browsers. IE 9+
  • Access-Control-Allow-Origin: *

OData

  • Edm Model != Entity Framework Model.
  • Discover
  • $select to pull specific columns. Can be useful to exclude image data columns.
  • ODataConventionModelBuilder
  • Makes Services Easier.

DEV310 Not MacGyver's JavaScript - Better Client Side Architectures.
  • jQuery - DOM abstraction library - Gets complicated really quickly. Should be used as a single tool rather than a soltuion to everything. Focus on the object model.
  • Frameworks - generally prescriptive, sometimes restrictive. Hollywood principl.
  • Library - generally focused and to the point.
  • Backbone.js Library
    • Models - data and associated functions
    • Views - UI backed by a model
    • Events - Bind and trigger custom events
    • Router - Provide linkable URLs
  • Problems with backbone:
    • Complexity isues with scaling.
    • Headaches with Routing Insanity.
    • Events can become really complex.
    • Memory Leaks (Zombie Views) View Events didn't unbind.
    • Most of the pain happens in the Router and the View.
  • "The secret to building large apps is never build large apps. Break your...
  • Modula/ Component Application.
    Modules are decoupled from each other. Removing one does not affect the other.
  • Application Orcastration as a first class concern. Responsible or the orchstration of the modules.
  • Marionette.js - helps build composite apps with backbone.
    Backbone extensions to remove boilerplate code. (ItemView, CollectionView)
    Avoids ZombieViews by unbinding.

INO301 Building Apps with the Kinect for Windows SDK
  • v1.5 More Sensor data, IR, Accelerometer, Camera Settings.
  • 1.7 Kinect Fusion. 3D scanning.
  • Kinect will consume about 60% of a single physical USB port.
  • Stride, # of bytes per single line

Day Three


DEV312 Pick your poison; pick your target - multi-platform development with .NET

Xamarin

C# with the .NET rather than the JVM

  • It is not write once use everywhere. UI created differently for each platform. Would otherwise give you lowest common denominator.
  • iOS will run ARM Binary to run natively. Ahead of time compilation. Certain things like reflection and generics won't work.
  • Android can run IL+JIT
  • Can run Windows, Android and iOS emulators.
  • "On the Mac, when it's time to upgrade, you just pick it up, throw it away, and buy a new one."
  • Ensure Windows VM uses two cores. One for its internal VM. Enable HyperV
  • Project Linking

APP213 Game On - Cross Platformer
  • DoDo gogo using - HTML5, impact.js, Canvas. Three.js
    HTML Drawbacks.
    • Draw Call Efficiency. Particle Effects. High Asset Count
    • Audio Management (good), but not fine grained.
    • Tooling - not storing tools for HTML games development.
  • Unity IDE for games
  • Example games using Unity - Jelly Run. Template Run
  • Advantages:
    • Pipeling - import photoshop file.
    • Tooling - All the tools to manage and manipulate a game.
    • Performance Tuning
    • Asset Store - get assets.
    • 3D
    • 2D (Unity 4.2 built in)
    • Multi-Platform deployment.
  • Code Typically written in C#. Runs on mono and targets .NET 3.5
  • Can pull .NET 3.5 Libriaries into the Unity Assets/Plugins folder.
  • Basic support for async/await. But doesn't extend to Task return types.
  • Use common assembly name between Unity .NET and Windows 8 Library to work with both.
  • Unity can process each asset on import and adjust to suit the platform. E.g. down sample for Windos phone.
  • Build config on Phone Solution to "Master" (rather than debug and release) have debug support.
  • Shaders run on the graphic card. Shader runs on Materials.
  • Cross Platform Considerations.
    • - Store approval requirements
    • - Automated certification tests
    • - Start packaging early
  • -
  • Know Your Devices
    • - High memory
    • - Low memory
    • - Resolution
    • - Graphics capabilities
    • - Aspect rations
    • - Device Capabilities
  • Implement anaylitcs. The most popular level may be the hardest level. Nuget import for anaylics in Windows phone.
  • Unity3D.com
  • Unity Answers

DEV414 Taming Time: A Deep Dive into the Reactive Extensions
  • The async await pattern does not compose very well.
  • IObservable. Nothing in .NET 4 implements this interface.
  • Reactive Extensions - where to get the IObservable and how to work with them.
  • IObservable.Subscribe - OnCompleted, OnError, OnNext
  • RE - Subscribe takes a delegate/callback.
  • Dispatchers . Invoke. Instead use .ObserveOn() so it runs on the dispatcher thread.
  • .Timestamp()
  • .DistinctUntilChanged()
  • IQbservable - passes query off to the remote datasource and will only the filtered results.
  • Applies the filters much earlier.

DEV316 Getting started with Git: A .NET developer's guide

Ian Randall

  • Record changes to file(s)
  • Restore
  • Who made the changes
  • Centralised VCS.
    • - Collaborate in teams
    • - Server contains history
    • - Client contains working copy.
  • Issues:
    • - Heavy network usage / slow
    • - Single point of failure
    • - Typically poor offline experience
  • Distributed VCS
    • - Repositories
    • - Fully offline
    • - Mostly local commands - fast
  • git-scm.com/doc
  • Basic commands
    • $ git init MyProject
    • $ git add Readme.md
    • $ git status Changes
  • Files must be added to the staging area.
  • Commit - Commit changes to the repo. Working directory clean
  • $ git commit -m "Added Readme"
  • Unstaging - reversing add
  • $ git reset HEAD
  • Unmodify changes
  • $ git checkout --
  • Branching - Git's killer feature
  • snapshots - Git doesn't store deltas. It stores the whole file. Uses compression in storage.
  • Metadata
  • Pointers
  • A commit contains:
  • pointer to the sanpshot...
  • Labels for HEAD and master.
  • $git branch
  • $git checkout
  • Moves HEAD to the feature branch.
  • Merge or Rebase.Rebase can make it easier to read the history, but alters the previous SHAs. Rebase best when only done locally to code that isn't pushed to others.
  • Distributed
  • Git on the Server - Subtly different to client/server
  • Git clone <path>
    <ssh://user@>
    user@server:project.get
    https://foo.bar
  • $ git remote - verbose
  • $ git remote add alias <foo>
  • Remote branch
  • Pull the latest versions from the server.
    $git fetch origin
  • $git fetch
  • $git merge
  • $git pull
  • Push to remote
  • $ git push origin master
  • Pull Requests - Asking someone else to get your changes into their repository.
  • Git support in Visual Studio
    • - Select 'Git' as Source Control type in VS2013
    • - Integrated experience
    • - Brand new, but maturing
  • Git Extensions very good on windows.

DEV415 The conjurer's masterpiece - hiding complexity with async

  • "Asynchronous programming involves the coordination of multiple concurrent processes"
  • Blocking can be dangerous:
    • Scarce resources (threads): UI threads (this is only one), Javascript, I/O
    • Expensive resources: .NET ~1MB per thread memory usage. Threads are only added to the ThreadPool slowly.
    • Too many processes to coordinate. 'Duplex' connnections - long running process per user
  • Callbacks split implementation up. Intention is out of sequence.
  • Promises - Ordering correct, but exception handling is hard. Plus a large amount of ceremony code.
  • async/await - resembles the blocking code flow structure to make following the process easier. Exception handling matches the standard synchronous technique.
  • Async is a "MethodBuilder iterating over tasks and awaiting on the results"
    • Tasks - The results or promise of a result from asynchronous methods
    • Awaiters - Holds a collection of continuations, TaskAdapter acts as adapter for a Task
    • MethodBuilder - Coordinates the running of an async method. How does it iterate over the Tasks.
    • Continuations - What do I run when the task is finished?
    • Schedulers - How do I run the continuation
  • Practical async in C# - 6 things to know
    • Use TaskCompletionSource to create your own Tasks -
    • Make sure all Tasks are observed. If it returns Task make sure you await it. Important for exception handling.
    • Be careful with async void - can't await for the results and can't catch exceptions. Rule of thumb - "async void is only for event handlers at the top of the stack."
    • Use .ConfigureAwait(false) when possible - help avoid multi-threading issues. Don't come back on the same thread if the returning thread isn't important. Useful for library code.
    • Async void can still be unit tested -
      await TaskTrackingSynchronizationContext.WaitForAsync();
    • Visual Studio 2013 - Simplified debugging - Windows > Tasks - Shows all tasks that are currently active and improved stack trace.

Other interesting talks:

Thursday, August 29, 2013

Introduction to the Leap Motion with .NET Presentation

Here is the presentation I gave recently on using the Leap Motion from .NET. There are a number of demos that go with it that aren't covered here.

Wednesday, August 7, 2013

Checking the FormsAuthentication cookie size is within 4096 bytes

I recently encountered an issue with the FormsAuthentication cookie not being set for certain users.

It turns out the cause was the total cookie size exceeding 4096 bytes and the browser not accepting it.

Aside from fixing the root cause and as a preventative measure for the future, I've added something like the following to detect the excessive cookie size. Note that this is a bit approximate as it doesn't take into account the cookie name, expiry date, etc...

    FormsAuthenticationTicket ticket = // Separate code to setup the authentication, including the UserData

    string hash = FormsAuthentication.Encrypt(ticket);
    int maxByteSize = 4000; // Max Cookie Size is 4096 including Cookie Name, Expiry, etc...
    if (System.Text.ASCIIEncoding.ASCII.GetByteCount(hash) > maxByteSize) 
    {
        // Raise the alarm that the cookie is going to get rejected by the browser
    }
    
    // Continue with standard cookie setup...
    HttpCookie formsAuthCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);

Thursday, May 23, 2013

Barcode Wallet for Windows 8

About Barcode Wallet for Windows 8

Save space in your wallet by digitizing the barcodes of any loyalty or memberships cards that you carry around.

Features:

  • See your most used barcodes at a glance
  • Tap a card to quickly bring up the barcode ready for scanning.
  • Pin your most used cards to the start screen.
  • Scan a barcode directly from a video feed, photo, or saved image.
  • Share generated barcodes with other apps
  • Backup and restore barcodes to Skydrive. Works with the companion Windows Phone app.
  • Pin barcodes for quick access from the start screen
  • Search for barcodes by name, including close match recommendations
  • Read barcodes directly from content shared from other apps

Report an issue or bug

You can submit any issues, bugs or feature requests here.

Tips and FAQ

Scanning Barcodes in

  • Ensure that the complete barcode can be seen clearly in the photo
  • Try to avoid the flash or external light source over saturating the barcode
  • Orientate the barcode to match the devices orientation
  • Check that the barcode format is supported by the app.
  • If you are having issues with a particular barcode try sending an image of it to an online reader. I've found the ClearImage Free Online Barcode Reader / Decoder to work well and provide back useful information, such as the barcode type as well as the data.

Scanning barcodes directly from the computers screen

Unfortunately not all types of barcode scanner are capable of reading barcodes directly from a screen. The major factor is the type of scanner being used.

A laser scanner sends out beams of light and uses the reflected light to read the light and dark bars. White bars reflect back the majority of the light. Black bars absorb the majority of light and reflect back very little. Therein lies the issue for scanning a barcode from a cellphone screen. Firstly, The glass and other layers of a cellphone screen are more reflective than a printed barcode. The excess light they reflect back will prevent the scanner from clearly seeing the difference between light and dark portions of the barcode. Secondly, a cellphone screen does not appear white because it is reflecting light. Rather, it is emitting light from a number of other colours to create white (typically red, green and blue pixels). These multiple pixels emitting light together won't reflect light in the way that a printed white does. For these reasons a laser scanner cannot read a barcode from a phones screen.

Another type of scanner is an imager or CCD Barcode scanner. These work more like a digital camera and will see the light emitted from the screen. CCD scanners can read a barcode from a cellphone screen.

See also:

  • POSGuys - Can I scan barcodes directly from a cell phone or similar device?
  • POSGuys - What is the difference between laser barcode scanners and imagers, also known as CCD barcode scanners?

Barcode Wallet

Barcode Wallet Privacy Policy

Barcode Wallet does not collect or publish any personal information.

This app is supported by ads from Microsoft Advertising. Learn more about Microsoft’s privacy practices and your choices. Learn more link: https://choice.microsoft.com/AdvertisementChoice/

Friday, May 3, 2013

Windows 8 Simple Toast Notifications from running app

I wanted to add a very basic toast notification for an actively running windows 8 app to indicate that a long running process has been completed. At the most basic level I needed to build up some XML and use it to create a ToastNotification that is shown via the ToastNotifier. E.g.

    using Windows.UI.Notifications;

    //...

    Windows.Data.Xml.Dom.XmlDocument toastDOM = new Windows.Data.Xml.Dom.XmlDocument();
    toastDOM.LoadXml(@"
  
    
      Body text that wraps over three lines
    
  
");

    ToastNotification toast = new ToastNotification(toastDOM);

    ToastNotifier tn = ToastNotificationManager.CreateToastNotifier();
    tn.Show(toast);

However, when run, the ToastNotifier has the Setting value "DisabledByManifest". So somewhere in the Package.appxmanifest I need to enable toast notifications. Apparently it is "in the Notifications section of the Application UI tab" (Source).

I couldn't see it initially. After a bit of hunting I found it under "All Image Assets".

Thursday, May 2, 2013

Custom TopAppBarButtonStyle to mimic the Windows 8 Weather app TopAppBar

The Windows 8 Weather app uses a top app bar for flat (rather than hierarchical) navigation between Home, Places, and World Weather pages. It appears at the top of the page and uses square controls rather than the rounded ones used by the bottom app bar for commands.

With a C# and XAML project you can get started with the bottom app bar pretty quickly using the Styles derived from

AppBarButtonStyle
in the /Common/StandardStyles.xaml that comes with most new projects. There isn't however an equivalent style for TopAppBarButtonStyle that can be used in the TopAppBar.

I've started down the path of defining my own style, but didn't complete it as I decided against used the navigation bar with an otherwise hierarchical app. It is still very much a work in progress, but placed here for when I need it again.

In StandardStyles.xaml

    <Style x:Key="TopAppBarButtonStyle" TargetType="Button">
        <Setter Property="Width" Value="150"/>
        <Setter Property="Height" Value="100"/>
        <Setter Property="Background" Value="#FF3F3F3F" />
        <Setter Property="BorderBrush" Value="#FF3F3F3F" />
        <Setter Property="FontFamily" Value="Segoe UI Symbol"/>
        <Setter Property="FontWeight" Value="Normal"/>
        <Setter Property="FontSize" Value="28"/>
        <Setter Property="HorizontalContentAlignment" Value="Left"/>
        <!--HorizontalAlignment="Right"-->
        <Setter Property="Template">
            <Setter.Value>

                <ControlTemplate TargetType="Button">
                    <Grid>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal" />
                                <VisualState x:Name="PointerOver">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="Background">
                                            <!--<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ButtonPointerOverBackgroundThemeBrush}" />-->
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="#FF242424" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ButtonPointerOverForegroundThemeBrush}" />
                                            <!--<DiscreteObjectKeyFrame KeyTime="0" Value="#FF242424" />-->
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Pressed">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="Background">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ButtonPressedBackgroundThemeBrush}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ButtonPressedForegroundThemeBrush}" />
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="Background">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ButtonDisabledBackgroundThemeBrush}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="BorderBrush">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ButtonDisabledBorderThemeBrush}" />
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource ButtonDisabledForegroundThemeBrush}" />
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="FocusStates">
                                <VisualState x:Name="Focused">
                                    <Storyboard>
                                        <DoubleAnimation Storyboard.TargetName="FocusVisualWhite" Storyboard.TargetProperty="Opacity" To="1" Duration="0" />
                                        <DoubleAnimation Storyboard.TargetName="FocusVisualBlack" Storyboard.TargetProperty="Opacity" To="1" Duration="0" />
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Unfocused" />
                                <VisualState x:Name="PointerFocused" />
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <Border x:Name="Border" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Margin="3" Padding="0,10,0,0">
                            <StackPanel HorizontalAlignment="Left" Width="140" Margin="10,0">
                                <ContentPresenter x:Name="ContentPresenter" Content="{TemplateBinding Content}" ContentTransitions="{TemplateBinding ContentTransitions}" ContentTemplate="{TemplateBinding ContentTemplate}" Margin="{TemplateBinding Padding}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                                <TextBlock
                                    x:Name="TextLabel"
                                    Text="{TemplateBinding AutomationProperties.Name}"
                                    Foreground="{StaticResource AppBarItemForegroundThemeBrush}"
                                    Margin="0,0,2,0"
                                    FontSize="14"
                                    TextAlignment="Left"
                                    MaxHeight="32"
                                    TextTrimming="WordEllipsis"
                                    Style="{StaticResource BasicTextStyle}"/>
                            </StackPanel>
                        </Border>
                        <Rectangle x:Name="FocusVisualWhite" IsHitTestVisible="False" Stroke="{StaticResource FocusVisualWhiteStrokeThemeBrush}" StrokeEndLineCap="Square" StrokeDashArray="1,1" Opacity="0" StrokeDashOffset="1.5" />
                        <Rectangle x:Name="FocusVisualBlack" IsHitTestVisible="False" Stroke="{StaticResource FocusVisualBlackStrokeThemeBrush}" StrokeEndLineCap="Square" StrokeDashArray="1,1" Opacity="0" StrokeDashOffset="0.5" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style x:Key="HomeTopAppBarButtonStyle" TargetType="Button" BasedOn="{StaticResource TopAppBarButtonStyle}">
        <Setter Property="AutomationProperties.AutomationId" Value="HomeTopAppBarButtonStyle"/>
        <Setter Property="AutomationProperties.Name" Value="Home"/>
        <Setter Property="Content" Value=""/>
    </Style>

In the page:

    <common:LayoutAwarePage.TopAppBar>
        <AppBar Height="150">
            <StackPanel  Orientation="Horizontal" Grid.Column="1" HorizontalAlignment="Left">

                <Button x:Name="homePageButton" 
                    Click="HomeButtonClick"
                     Style="{StaticResource HomeTopAppBarButtonStyle}"/>
            </StackPanel>
        </AppBar>
    </common:LayoutAwarePage.TopAppBar>

See Also:

Monday, March 4, 2013

Adding async/await support to WP7 projects

When porting changes made to a Windows Phone 8 app back to the Windows Phone 7.x version I ran into an issue due to the lack of async/await support.

Turns out you can add the Microsoft.Bcl.Async Nuget package to add support for Async in Windows Phone 7.x. Note that at this time it is prerelease, so you may need to indicate as such to nuget to install it.

Once added I could then create some extension methods for the Live SDK to convert the event pattern to the async pattern:

    public static class LiveConnectClientExtension
    {
        public static Task GetAsyncTask(this LiveConnectClient client, string path)
        {
            var tcs = new TaskCompletionSource();
            client.GetCompleted += (s,e) => 
            {
                if (e.Error != null) tcs.TrySetException(e.Error);
                else if (e.Cancelled) tcs.TrySetCanceled();
                else tcs.TrySetResult( new LiveOperationResult(e.Result, e.RawResult));
            };
            client.GetAsync(path);
            return tcs.Task;
        }
    }

Critical Sections

Now that things are occurring asynchronously their is the possibility of the user triggering multiple threads. See Awaitable critical section for a tidy solution.

See Also:

Tuesday, February 26, 2013

Windows Phone - NZ Tides

About NZ Tides for Windows Phone

Tidal predictions for New Zealand ports using data from LINZ.

Values are for standard barometric pressure.

Features:

  • View High and Low tide times and heights for a given day between 2011 and 2013 inclusive.
  • Use the graph and slider to calculate tide heights for a given time of day.
  • No network connection is required, all data is embedded within the app.
  • Select port by name or from a map
  • Automatically adjusts times for daylight savings
  • View the tides levels for the current month.

Versions:

  • 2.1
    • Pin individual ports
  • 2.0
    • Locations can now have aerial maps (optional)
    • Reformatted date and time selection. The slider can be toggled in.
  • 1.2
    • Added secondary ports.
    • Pin a location to the live tile.
    • Hide unused Locations.
    • Calculate sunrise and sunset times for location.
  • 1.1
    • Fix for issue with tide graph on year transition.
    • Tapping the rise or set times in the compass view will toggle to showing the time until the event occurs.

Tips and FAQ

Customising locations

The "add locations" application bar button can be used to show and hide primary ports and to remove any secondary ports that have been added to the locations.

Tuesday, February 19, 2013

Making a Salesforce Id case insensitive in Excel

I have an Excel spreadsheet with a large number of rows. Each row includes the 15 character case sensitive version of a Salesforce Id. I need to find the rows that contain duplicate Salesforce Ids.

With the 15 character Salesforce Ids being case sensitive, and Excel by and large being case insensitive this presents an issue.

Possible Solutions

  1. Export the data from Salesforce using the 18 character Salesforce Ids. These are specifically designed to be case insensitive.
  2. Use an Excel formula to create another column containing a case insensitive value.
    =CD2&CODE(MID(CD2,12,1))&CODE(MID(CD2,13,1))&CODE(MID(CD2,14,1))&CODE(MID(CD2,15,1))
    Here the cell CD2 contains the case sensitive Salesforce Id.
    This formula is appending the ASCII character value for each of the last 4 characters in the ID.
    For example, an ID that ends with "yBSe" will have "1216683101" appended.
    You may need to extend the number of checked characters if you have a large number of records. As it is only the last 4 characters of the input Id will be case checked.
  3. Use VBA to calculate the 18 character case insensitive values.
    Place the following into a VBA module.
    Function FixID(InID As String) As String
    ' Converts a 15 character ID to an 18 character, case-insensitive one ...
    Dim InChars As String, InI As Integer, InUpper As String
    Dim InCnt As Integer
    InChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"
    InUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    
    InCnt = 0
    For InI = 15 To 1 Step -1
       InCnt = 2 * InCnt + Sgn(InStr(1, InUpper, Mid(InID, InI, 1), vbBinaryCompare))
       If InI Mod 5 = 1 Then
           FixID = Mid(InChars, InCnt + 1, 1) + FixID
           InCnt = 0
           End If
        Next InI
        FixID = InID + FixID
    End Function
    

    Then reference the function directly in a formula.

See Also:

Wednesday, January 23, 2013

Using the Burp Suite to test a Web Service that is consumed in a Salesforce app

The following steps can be used to run the Burp Suite scanner against a Web service that is consumed in a Salesforce app via callouts.

The basic idea is to:

  1. import the Web Service WSDL into SOAP UI,
  2. configure SOAP UI to use the Burp Proxy,
  3. use SOAP UI to simulate the SOAP requests for typical use cases, This will require updating the sample requests generated in SOAP UI to represent those made from Salesforce under normal usage.
  4. select the requests to scan from the Burp Target, Site map tabs

Get a Burp Suite License

ISV partners can submit a Burp License Request.

Install and run Burp

I put the Burp jar file and license txt file in a directory and started it with the following in a batch file:

java -jar -Xmx1024m burpsuite_pro_v1.5.04.jar

See Also: Getting Started With Burp Suite

Configure Burp

Turn “Intercept” (Proxy->Intercept) off within Burp.

Configure SOAP UI to use the Burp Proxy

File > Preferences > Proxy Settings:

127.0.0.1:8080
You can find the Burp Proxy details Under Proxy > Options > Proxy Listeners

You may need to installed Burp's generated CA Certificate into the Trusted Root Certification Authorities tab if using SSL. See Installing Burp's CA Certificate. If not configured you get the following error message in Soap UI "Error getting response; javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated."

For SoapUI to pickup the new cert:

  1. Go to the path: C:\Program Files (x86)\SmartBear\SoapUI-5.0.0\jre\lib\security
  2. Export the Burp CA Certificate using Proxy > Options > CA certificate... > Export: Certificate in DER format.
  3. Use the Java keytool executable to import the certificate:
    "C:\Program Files (x86)\Java\jdk1.7.0_67\bin\keytool.exe" -import -alias burp -file "C:\WhereYouExportedTheDerCertificate\PortSwiggerCA.cer" -keystore cacerts
  4. The keystore password will be:
    changeit

Use SOAP UI to simulate the web requests that Salesforce would make to the web service

This will require you to update the sample requests that SOAP UI generates for each of the web methods with realistic request data. Try to mimic the calls that Salesforce will be making.

When the SOAP UI requests are submitted Burp will record them under the Target > Site map tab.

Start the Burp Scanner

Under the Target > Site map tab select the request nodes or host/branch that you want to scan. If it was a website you would usually do an "Spider this branch" at this point. Start the Scanner for the branches by selecting "Actively scan this branch".

Under the Scanner > Scan Queue tab the requests will appear and be processed. The output will start appearing under the Scanner > Results tab.

Export the Burp Scanner Results

Under the Scanner > Scan Queue tab select the results of interest then right click and select "Report selected issues"

The Printer-friendly version with hyperlinks works well for both screen reading and printing. Defaults can be used for the remaining steps. Ensure you save the report in a file with the ".html" extension.


See Also: