Coding and other programming stuff for coding junkies :)
Don't wanna be here? Send us removal request.
Text
Single Selection Collectionview deselect
When using UICollectionView’s with the default single selection type. Deselecting the cell can be an issue and none of the deselect Delegate methods get called :/
So how to work around it?
Utilising another delegate method “shouldSelectItemAtIndexPath” you can detect whether a cell is selected or not and respond accordingly.
func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
let cell = collectionView.cellForItemAtIndexPath(indexPath)
if let selected = cell?.selected where selected {
//Preform any custom deselect logic
collectionView.deselectItemAtIndexPath(indexPath, animated: false)
return false
}
return true
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//Preform selection logic
}
0 notes
Text
Swift - Generate Objects and Basic IOC
IOC in swift is a difficult problem to solve. Generics and reflect as still very immature so creating an instance on an object in pure swift is difficult.
Most of the solutions I could find utilise objective-c. Which is find for class that conform to NSObject or have the flag obj-c. So what about swift objects
Basic Constructor
One solution is to use dictionary containing closures that return an instance of your object.
You can then retrieve an instance of an object by calling the get function on the injector.
let simpleService: Service1 = Injector().getSimpleClass(Service1)
class Injector { var lookupMap: [String: (() -> AnyObject)] { return [ "SampleViewContoller": { SampleViewContoller(dependency: someDependency() ) }, "SampleViewContoller1": { SampleViewContoller1() }, "Service1": { Service1() } ] } func getSimpleClass<T: AnyObject>(type: T.Type) -> T! { let className = NSStringFromClass(type).componentsSeparatedByString(".")[1] return lookupMap[className]!() as? T } }
0 notes
Text
Programmatic Autolayout in Swift
Im sure we have all experienced the joys of autolayout. Its fantastic when it goes well, but when it goes wrong your in a world of pain.
The easiest way to using autolayout is though interface builder but what about views that and created programmatically??
Swift provides a way to manipulate your views dynamically without the need to manually set frame position which will inevitably go wrong.
A NSLayoutConstraint must first be created that maps the relationship between the parent view and child.
The below sample, creates a constraint which positions newView in the CenterX of the parent.
NSLayoutConstraint(item: newView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 0)
This constraint must then be applied to the parent view to enable so the layout can take place.
let centerX= NSLayoutConstraint(item: newView, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 0)
self.view.addConstraint(centerX)
Autolayout Not Working?
In order to get the constrains to change the views layout, autoresizingmask must be set to false.
newView.setTranslatesAutoresizingMaskIntoConstraints(false)
Full Example
let newValue = UIView(frame: CGRect(0,0,300,300))
newValue.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(newValue)
let centerX = NSLayoutConstraint(item: newValue, attribute: .CenterX, relatedBy: .Equal, toItem: self.view, attribute: .CenterX, multiplier: 1.0, constant: 0)
self.addConstraint(centerX)
let centerY = NSLayoutConstraint(item: newValue, attribute: .CenterY, relatedBy: .Equal, toItem: self.view, attribute: .CenterY, multiplier: 1.0, constant: 0)
self.addConstraint(centerY)
0 notes
Text
OSX Keychain and ProvisioningProfile
I've created a simple keychain management gem, making it simple to control certificates and provisioning profiles.
I created this gem to solve a problem when signing our apps on CI.
How to use
Install the gem
gem install keychain_osx
The follow code creates a temporary keychain that is deleted after the block has completed. Inside the block a P12 is inserted into the keychain using the import methods.
require 'keychain_osx'
OSX::Keychain.temp do |keychain|
keychain.import('PrivateKey.p12','password')
end
Provisioning Profile
Provisioning Profile are a key part to signing any app. To install a profile inside the xcode.
Using the Provided ProvisioningProfile class like below:
OSX::ProvisioningProfile.new('ROVISONING_PROFILE').install
0 notes
Text
Re-signing Apps created by an external developer
When you work with 3rd party developers, at the end of the project we need to re-sign the published ipa with our bundleID and certificates. All we are provided with is an ipa that has been signed with the developers certificates but we are unable to upload them into the app store.
You will need the following:
The Mobile Provisioning Profile
A iOS Distribution Certificate
Entitlements.plist (See below is unsure how to create)
Creating Entitlements.plist
To create the an Entitlements plist open the Provisioning Profile in atom
Inside this file there is a key called “Entitlements” Copy the <dict> section and paste this into a plist file
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>application-identifier</key> <string>PREFIX.yourappBundleID</string> <key>aps-environment</key> <string>production</string> <key>get-task-allow</key> <false/> <key>keychain-access-groups</key> <array> <string>PREFIX.yourappBundleID</string> </array> </dict> </plist>
Re-sign the .IPA
Unzip the ipa using the below command
unzip -o /path/to/YourApp.ipa -d /path/to
Inside the extracted folder you can will find an Info.plist
Open the files and update the BundleID. Saving the file
Locate the ‘embedded.mobileprovision’ and replace with you new Mobile Provisioning Profile being sure to rename it to embedded.mobileprovision
Run the below command to resign the app with the new details
codesign -f -s “iOS Distribution Certificate Name" -i "PREFIX.yourappBundleID" --entitlements "entitlement.plist" -vv Payload/MyApp.app/MyApp
Rezip Payload folder and rename to .ipa
0 notes
Text
iOS8 Launch Screen
In previous ios versions you would create a launch asset catalog containing the different image resolution that would be used on depending on the version. With the introduction of iOS8 there is now a new way.
Interface Builder
First create a new file from under "User Interface" and select the option called "Launch Screen"
Using autolayout design the first view of you app so it scales to suit all resolutions that your app supports.
Using the new Launch Screen
Under the app setting select the newly created Launch Screen from the app options.
0 notes
Text
Swift using and testing notifications
I think everyone would agree the notification pattern within objective-c is a great way to decouple views from services.
Swift implementation
Posting a notification in swift is similar to the objective-c implement just with the new syntax.
NSNotificationCenter.defaultCenter.postNotification(name: “notificationName”, object: nil)
When adding an observer to the Notification Center in swift. The class that is being set as the observer must be an objective-c type (Derive from NSObject). When the class isn’t an objective-c type, when the notification selector fires and exception is thrown crashing the app.
NSNotificationCenter.defaultCenter.addObserver(selector: “methodToInvoke:”, name: “notificationName”)
fund methodToInvoke(notification: NSNotification) { //Do Stuff }
Testing NSNotificationCenter
Currently this is no native mocking framework for swift meaning the only viable way to mock object is using hand rolled mocks.
In the test target create a new swift class called: MockNSNotificationCenter. In the new class, subclass NSNotificationCenter then override the methods your test is expecting to call as described below:
class MockNSNotificationCenter: NSNotificationCenter {
var observerCount = 0
var postCount = 0
var lastPostedNotificationName:String?
override func addObserver(observer: AnyObject, selector aSelector: Selector, name aName: String?, object anObject: AnyObject?) {
observerCount++
}
override func postNotificationName(aName: String?, object anObject: AnyObject?) {
lastPostedNotificationName = aName!
postCount++
}
}
Then in your real class you use lazy instantiation to allow the mock notification center to be injected.
class RealClass {
lazy var notificationCenter: NSNotificationCenter = {
return NSNotificationCenter.defaultCenter()
}()
func someMethodPostNotification() {
notificationCenter.postNotification(name: “notificationName”, object: nil)
}
}
In your test class you can assert that a notification is posted when a method is called
class RealClassTests: XCTestCase {
let sut = RealClass()
let mockNotification = MockNSNotificationCenter()
func testNotification() {
sut.notificationCenter = mockNotification
sut.someMethodPostNotification()
XCTAssertEqual(mockNotification.postCount, 1, "a notification should be posted")
}
}
0 notes
Text
Clean room continuous integration
As developers and testers, how many time have we said or heard the phrase; "it works on my machine".

We deploy our code to source control and CI run and subsequently fails.
Not because of our tests, but because another project requires a different setting to be enabled or a previous build changed a setting.
We spend time trying to find a solution that will work for both projects. Why? If each project had its own space we wouldn't have any of these issues. So there the solution, each project has a decided build machine???
Visualization Using Vagrant
Vagrant is a tool that create Virtual Machines based on a base box which I pre-configured and stored inside the vagrant application. When vagrant up is called a new VM based on the basebox template is created. Then, once no longer required the VM is removed completely.
Using Vagrant with CI
Vagrant build Steps:
A build is started
A new VM is created from the basebox
The project is copied to the VM
The CI tasks run
The VM is destroyed
Benefits
Every build is run in a clean room unaffected by other build.
This bring additional benefits such as repeatability and consistency.
To aid this process we have created some simple tools in ruby to stream line the CI process run in a clean environment:
Vagrant_CI
0 notes
Text
MNSRemoteAB
One of the challenges with mobile application is the inability to iterate on apps quickly due to the app verification process and users reluctance to update.
A/B Testing is a great way of testing new features on users but this still requires the app to be re-verification in order to increase the number of users that receive the feature.
We have created Remote AB testing....Using a remote configuration file hosted on a server that gets downloaded on each app starts you are able to increase and decrease the number users the receive the new feature.

When have created the package for all three platforms:
iOS
Android
Windows Phone (portable) : nuget
0 notes
Link
Checkout this open source project I have created to imitate the PaperFold-for-iOS
https://github.com/ChrisGriffiths/PageFold-for-WP8
1 note
·
View note
Text
WP8 BDD Functional Tests
I wanted to create app's that have end to end functional tests in the same was a I can for iOS or Android using Calabash.
After doing a load of research I came across a great little package called WindowsPhoneTestFramework by Expensify.
After installing to using this package with Specflow is quickly became apparent that it wasn't going to work.
Although all the work for WP8 had be developed alot of the code had been commented out or deleted so the packaged didn't work as expected.
Solution
I forked the repo and modified the code to make it work with WP8.
Now all the examples pass and I am currently using this in one of my projects
http://github.com/DigitalInnovation/WindowsPhoneTestFramework/tree/master
Take a look and see what you think!!!
0 notes
Text
RESTFULCLIENTSTUDIO
Hey Guys
So me and a buddy from work have been twinkering away for two weeks to make a simple FREE API tool.
introducing RestfulClientStudio
A Simple get and post restful client to test your services. The app will store a history of requests you do for quick access. Also you can create projects with set base urls for easy repeatable use.
Check it out
1 note
·
View note
Text
Passing Method to ICommand
Implementing MVVM with ICommands, can easily lead to complex ViewModel and CodeDuplication.
What the alternative!!!
A generic "Command" class where you pass you method to be executed into the constructor.
Here's the situation...
In my ViewModel I have a ObservableCollection that I want to be updated when a button is clicked.
I create a class called Command that implement ICommand Interface. Then create a Constructor which take an Action with type Object.
The canExecute sets the default button status to true;
protected Action<object> Action = null;
publicCommand(Action<object> action, bool canExecute = true)
{
this.Action = action;
this._canExecute = canExecute;
}
In you ViewModel create a method that executes your desired task.
private void SearchProduct(object searchTerm)
{
var search = searchTerm as string;
if(search == null)
return;
var productList = _productStore.ProductsWithSearchTerm(search);
foreach (var product in productList)
{
ProductCollection.Add(product);
}
}
Creat a property called Command of type ICommand then In the constructor initialise the property passing in the method name: "new Command(SearchProduct)"
0 notes
Text
Run Powershell From C#

I am creating a testing framework using C# as part of the setup and teardown I wanted to start and stop a Hyper-V.
Came across this Microsoft Library: System.Management.Automation
Which is available as a nuget package instead of an install: http://www.nuget.org/packages/System.Management.Automation/
var ps = PowerShell.Create(); ps.AddCommand("Stop-VM"); ps.AddParameter("-Name","VM_Name"); ps.AddParameter("-Force",true); ps.Invoke();
1 note
·
View note
Text
Custom UI Panels WP8
Custom UI Panels give you the ability to specify scrolling and positioning using one tag. This their for create a Template that can be reused.
First: Create a new Class which derives one of the Panel Classes
eg: StackPanel,Grid or Panel
Add the newly created object to xaml
Import the namespace: xmlns:local="clr-namespace:SampleApp"
Use the new Panel Like Any Other
So What's the Benefit
In your custom panel you can then add custom behaviour such as event-handler and animations.
For Example:
In the constructor you can register the events:
ManipulationDelta += MainPage_ManipulationDelta; ManipulationCompleted += MainPage_ManipulationCompleted;
These events can trigger animations or other behaviour:
//Create the Animation
var animation = new DoubleAnimation() { Duration = new TimeSpan(0, 0, 5), To = 0, AutoReverse = true
};
//Create a CompositeTransform
var transform = new CompositeTransform(); transform.TranslateX = 0; this.RenderTransform = transform;
var storyboard = new Storyboard(); storyboard.Children.Add(animation);
Storyboard.SetTarget(animation, this); Storyboard.SetTargetProperty(animation, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateX)"));
storyboard.Begin();
In the Storyboard.SetTarget is sets its self (CustomPanel) as the animation target
0 notes
Text
Windows Store App Selected Item Colour
When creating Windows store apps the default selected item colour is set according to the users theme.
How Do You Change It?
The easiest way by far is to use blend.
In blend, under "Objects and Timelines" right click the item you want to change -> Edit Additional Templates -> Edit a Copy..
This will create a detailed styling options in the XAML.
Find the name of the action you wish to change here and change the object Values to Suit
0 notes
Text
Microsoft Azure and Rake

I wanted to functionality test my API when a new version was uploaded to git. I was using Teamcity which ran the unit tests.
Problem!! In order to run the functionally test; it must first be build and deployed then the tests can be run.
So you deploy to staging/dev server. When the tests fail its difficult to roll back the chances.
Microsoft Azure is fantastic in the ability to setup and teardown WebService with simple powershell commands.
Why use rake not powershell???
My tests uses cucumber with the cucumber_rest_api, which can't be run from powershell
Ruby for creating a new a new Website:
puts %x{powershell.exe -command New-AzureWebsite #{websiteName} -verbose}
if($?.exitstatus ==1 )
raise methodName
end
puts is require in order to log the results back to the console.Then you get the exist status to check whether the step failed. And throw and error to prevent future steps.
0 notes